fail-fast vs fail-safe

fail-fast iterators fail-safe iterator
不允许在遍历的同时对集合进行修改 允许一边遍历一遍修改集合
出现ConcurrentModifiedException  
用原始集合去遍历集合中的元素 用原始集合的副本进行遍历
迭代器不需要额外内存空间 迭代器需要额外内存空间
ArrayList,Vector,HashMap ConcurrentHashMap
Fail-Fast Iterators Fail-Safe Iterators
Fail-Fast iterators doesn’t allow modifications of a collection while iterating over it. Fail-Safe iterators allow modifications of a collection while iterating over it.
These iterators throw ConcurrentModificationException if a collection is modified while iterating over it. These iterators don’t throw any exceptions if a collection is modified while iterating over it.
They use original collection to traverse over the elements of the collection. They use copy of the original collection to traverse over the elements of the collection.
These iterators don’t require extra memory. These iterators require extra memory to clone the collection.
Ex : Iterators returned by ArrayListVectorHashMap. Ex : Iterator returned by ConcurrentHashMap.

猜你喜欢

转载自blog.csdn.net/weixin_39590058/article/details/87968819