What are fail-safe & fail-fast Iterators in Java

后端 未结 4 961
醉话见心
醉话见心 2020-11-29 15:11

There are two types of iterators in Java: fail-safe and fail-fast.

What does this mean, and is the difference between them?

4条回答
  •  一生所求
    2020-11-29 15:58

    This scenario relate with "concurrent processing", means that more then one user accessing the same resource. In such situation, one of the user try to modify that resource which cause the 'ConcurrentProcessingException' because in that case other user get improper data. Both this type relate with this kind of situation.

    In simple term,

    Fail-Fast :

    • Iterators immediately throw ConcurrentModificationException if structural modification(add, update, delete) happens.
    • Example : ArrayList, HashMap, TreeSet

    Fail-Safe :

    • Here Iterators not throw any exception because they operate on the clone of the collection, not original one. So, that they are fail-safe iterators.
    • Example : CopyOnWriteArrayList, ConcurrentHashMap

提交回复
热议问题