Concurrent modification error when adding elements to LinkedList

后端 未结 3 1800
长情又很酷
长情又很酷 2021-01-24 01:09

I have an List of LinkedList objects.

    List> backup = new ArrayList>();

The Link

3条回答
  •  醉梦人生
    2021-01-24 01:33

    java.lang.Colletions from JDK 1.5 is not synchronized. In earlier version(jdk 1.4), you wont find this problem.

    There are multiple solutions available for these problem and you need to choose one of them wisely as per your use case.

    • Solution 1: The list can be converted to an array with list.toArray() and iterate on the array. This approach is not recommended if the list is large.

    • Answer 2: The entire list can be locked while iterating by wrapping your code within a synchronized block. This approach adversely affects scalability of your application if it is highly concurrent.

    • Answer 3: JDK 1.5 gives you ConcurrentHashMap and CopyOnWriteArrayList classes, which provide much better scalability and the iterator returned by ConcurrentHashMap.iterator() will not throw ConcurrentModificationException while preserving thread-safety.

    • Answer 4: Remove the current object via the Iterator “it” which has a reference to the underlying collection “myStr”. The Iterator object provides it.remove() method for this purpose.

提交回复
热议问题