ConcurrentModificationException only in Java 1.8.0_45

前端 未结 4 927
余生分开走
余生分开走 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 11:01

    A ConcurrentModificationException is thrown by methods that have detected concurrent (i.e. in a separate thread) modification of an object when such modification is not permissible.

    The reason you're getting this exception is because you are modifying (sorting) the collection in a separate thread and iterating it.

    I quote from the ConcurrentModificationException javadoc:

    For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

    Source

    In your code, you are starting 500 threads that each sort and iterate over the list.

    Try sorting the list before you start your threads, and remove the call to Collections#sort from MyThread's #run().

提交回复
热议问题