一、fail-safe概述以及与fail-fast区别
首先 fail-safe 并不属于JavaSE规范术语,只是用以说明 fail-fast 与 non-fail fast 的区别。
这种机制的迭代器允许在迭代时修改集合,且不会抛出任何异常。不同的类实现方式有所不同,通常是因为"迭代"与"修改操作"使用的不是同一个数据数组,比如CopyOnWirteArrayList在修改时会创建一个原数组副本(只是新建一个数组,浅克隆)在新数组上修改后再将指针指向新数组,而此时迭代器中的指针仍指向原数组。
因此这种迭代器无法保证在迭代时获取的是最新数据,比如:(1)CopyOnWriteArrayList在迭代过程中的数据更新无法在迭代中表现出来。(2)ConcurrentHashMap的弱一致性迭代器。
注:弱一致性迭代器可能会(但不保证)将迭代过程中的修改表现出来。
ConcurrentHashMap迭代器官方注释:
The iterators returned by ConcurrentHashMap is weakly consistent. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed and may (but not guaranteed to) reflect modifications to the collection after the construction of the iterator.
二、示例
2.1 CopyOnWriteArrayList示例
public static void main(String args[])