What is ConcurrentModificationException? According to Oracle(TM) Java doc it is thrown when an object is modified but the operation should not be allowed at that time. I faced this issue when my application is built and ran using Java8. The same application was working fine with out any issue if I use Java7…There is absolutely no change on those functions…What went wrong?

The problem is, my app is having some in-memory cache objects which is built mainly using Java ArrayList. Since these are business critical data it will be accessed and updated (if needed) at run time. The cached data are returned to the caller after sorting and to sort we have written function like this,

Collections.sort(input, new Comparator() {
   public int compare(Object o1, Object o2) {
   // THIS FUNCTION DETAILS ARE OUT OF SCOPE
   }
});

If you have got a chance to look how the collections.sort implemented in Java 7, then, it will be something like below where it will copy the list to temporary object and sorts it. The result will be set in the list.

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    Object[] a = list.toArray();
    Arrays.sort(a, (Comparator)c);
    ListIterator<T> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);
    }
}

The same function is changed like below in Java8,

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

Little search on google will tell you that sort function is changed from Java 8 Update 20. Since the sorting happens on the same list object being passed to the sort() function it bails out when the list is modified while performing sort…The ArrayList implementation of Java 8 is like below,

public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

Hope it explains ! In my case, I manually had to change the call to Collections.sort() to my own collection where I copied the same function used by Java7. Well, I know it is ugly, I should better synchronize the application cache better but right now it looks like it will be another project for me 🙂

Leave a Reply

Your email address will not be published.

WP2Social Auto Publish Powered By : XYZScripts.com