Java Synchronized list

后端 未结 7 2135
一整个雨季
一整个雨季 2020-12-01 06:13

I have a pre-populated array list. And I have multiple threads which will remove elements from the array list. Each thread calls the remove method below and removes one item

7条回答
  •  盖世英雄少女心
    2020-12-01 06:43

    You can have 2 diffent problems with lists :
    1) If you do a modification within an iteration even though in a mono thread environment, you will have ConcurrentModificationException like in this following example :

    List list = new ArrayList();
    for (int i=0;i<5;i++)
       list.add("Hello "+i);
    
    for(String msg:list)
       list.remove(msg);
    

    So, to avoid this problem, you can do :

    for(int i=list.size()-1;i>=0;i--)
       list.remove(i);
    

    2)The second problem could be multi threading environment. As mentioned above, you can use synchronized(list) to avoid exceptions.

提交回复
热议问题