【发布时间】:2020-09-13 01:18:25
【问题描述】:
在同步集合中检查并发修改的快速失败机制是合理的,因为这些集合在多线程环境中被认为是线程安全的,因此它们应该知道并发修改。
但我很困惑,为什么像ArrayList 这样应该在单线程环境中工作的线程不安全集合也需要注意迭代中的并发修改?
感谢您提前回复!
【问题讨论】:
标签: java concurrency
在同步集合中检查并发修改的快速失败机制是合理的,因为这些集合在多线程环境中被认为是线程安全的,因此它们应该知道并发修改。
但我很困惑,为什么像ArrayList 这样应该在单线程环境中工作的线程不安全集合也需要注意迭代中的并发修改?
感谢您提前回复!
【问题讨论】:
标签: java concurrency
不要将“并发修改”中的“并发”误认为只指多线程。
您也可以在单线程代码中获得 ConcurrentModificationException:
List<String> list = new ArrayList<>();
list.add("");
Iterator<String> it = list.iterator();
list.add("");
it.next(); // ConcurrentModificationException
【讨论】:
ArrayList的文档中找到:The iterators returned by this class's iterator and listIterator methods are fail-fast [...] Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.