据我所知,有两种方法可以避免 ConcurrentModificationException,一个线程迭代集合,另一个线程修改集合。
- 客户端锁定,基本上在迭代期间锁定集合。其他需要访问集合的线程将阻塞,直到迭代完成。
- “线程限制”,克隆集合并迭代副本。
我想知道还有其他选择吗? 因为第一种方法显然是不可取的并且性能较差,如果集合很大,其他线程可能会等待很长时间。第二种方式我不确定,因为我们克隆集合并迭代副本,所以如果其他线程进入并修改原始集合,那么复制的集合就会变得过时,对吧?这是否意味着我们需要通过克隆重新启动并在修改后再次迭代它?
最佳答案
I am wondering are there any other alternatives ?
使用不会引发此异常的并发集合之一。相反,它们提供弱一致性。即,迭代时添加或删除的元素可能会出现,也可能不会出现。
http://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html
The java.util.concurrent package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided:
- BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.
- ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
- ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.
关于java - 避免 Iterator ConcurrentModificationException 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917264/