java - 避免 Iterator ConcurrentModificationException 的方法

标签 java multithreading concurrency iterator

据我所知,有两种方法可以避免 ConcurrentModificationException,一个线程迭代集合,另一个线程修改集合。

  1. 客户端锁定,基本上在迭代期间锁定集合。其他需要访问集合的线程将阻塞,直到迭代完成。
  2. “线程限制”,克隆集合并迭代副本。

我想知道还有其他选择吗? 因为第一种方法显然是不可取的并且性能较差,如果集合很大,其他线程可能会等待很长时间。第二种方式我不确定,因为我们克隆集合并迭代副本,所以如果其他线程进入并修改原始集合,那么复制的集合就会变得过时,对吧?这是否意味着我们需要通过克隆重新启动并在修改后再次迭代它?

最佳答案

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/

相关文章:

C#-BackgroundWorker不断更新控件: Error!

java - 缓冲迭代器实现

java - volatile 发布保证有多深?

java - 可以用Java实现twisted吗?

java - 如何使用java将GMT日期转换为MM/dd/yyyy

java - 从适配器替换时找不到 fragment ID 的 View

c# - 多线程和构造函数完整性

iphone - 在 iOS4 设备上后台发送大量数据的最佳实践?

go - 在 Go 中使用 channel ,我创建了一个返回地址的阶乘函数

java - 在jTextfield中显示jTable(char)数据