I stumbled over this odd bug. Seems like Collections.sort() does not modify the sorted list in a way that enables a detection of concurrent modifications when also iterating over the same list. Example code:
List<Integer> my_list = new ArrayList<Integer>();
my_list.add(2);
my_list.add(1);
for (Integer num : my_list) {
/*
* print list
*/
StringBuilder sb = new StringBuilder();
for (Integer i : my_list)
sb.append(i).append(",");
System.out.println("List: " + sb.toString());
/*
* sort list
*/
System.out.println("CurrentElement: " + num);
Collections.sort(my_list);
}
outputs
List: 2,1,
CurrentElement: 2
List: 1,2,
CurrentElement: 2
One would expect a ConcurrentModificationException, but it is not being raised and the code works although it shouldn’t.
Update: This answer was written for Java 6. With JDK 8u20’s Collection.sort now deferring to List.sort, Java 8+ now does throw an exception, although as pointed out by Brian Roach, it still doesn’t provide any guarantee to that effect.
Why would it throw
ConcurrentModificationExceptionwhen you are not adding/removing elements from your collection while iterating?Note that
ConcurrentModificationExceptionwould only occur when a new element is added in to your collection or remove from your collection while iterating. i.e., when your Collection is Structurally modified.sort wouldn’t structurally modify your Collection, all it does is modify the order.
Below code would throw
ConcurrentModificationExceptionas it add’s an extra element into the collection while iterating.If you look at the source of the
sortmethod in the Collections class, it’s not throwingConcurrentModificationException.Extract from the book java Generics and Collections: