ConcurrentModificationException only in Java 1.8.0_45

前端 未结 4 918
余生分开走
余生分开走 2021-01-19 10:36

I\'ve got two question about this code:

import java.util.*;

public class TestClass {

    private static List list;   
    public static void          


        
4条回答
  •  梦谈多话
    2021-01-19 10:48

    With Java 8, the Collections::sort method was reimplemented to delegate to the List::sort method. This way, a list can implement a more efficient sort algorithm if this is possible for the given implementation. For example, an ArrayList can use its random access property to implement a more effcient sorting algorithm than a LinkedList without random access.

    The current implementation for ArrayList::sort explicitly checks for modifications as the implementation is defined within the class and is capable of accessing iternal properties.

    Before Java 8, the Collections::sort method had to implement the actual sorting itself and could not delegate. Of course, the implementation could not access any internal properties of the specific list. The more generic sorting was implemented as follows:

    public static  void sort(List list, Comparator c) {
        Object[] a = list.toArray();
        Arrays.sort(a, (Comparator)c);
        ListIterator i = list.listIterator();
        for (int j=0; j

    The implementation first extracts a copy of elements and delegates the sorting to the implementation of Arrays::sort. This can not cause the observed exception as the sorting is conducted on a non-shared copy of elements. Later, the elements are updated element by element according to the sorted array by using a ListIterator.

    For an ArrayList, the ArrayList and its iterator keep track of the number of structural modifications, i.e. modifications that change the size of the list. If those numbers diverge for the iterator and the list, the iterator can know that the list was modified outside of its own iteration. It is however not capable of discovering that the elements of a list were altered as it happens for the Collections::sort implementation.

    The contract of a ArrayList does however not permit concurrent modifications in its contract. Despite the sorting not failing before Java 8, applying the sorting could lead to incorrect results. Since Java 8, it is however for the first time that this is discovered by the implementation.

提交回复
热议问题