What is Fail Fast vs Fail Safe Iterator in Java

In this tutorial we will learn what is Fail Fast what is  Fail Safe Iterator in java .

This is the one of the main question in interview regarding Concurrency management.Before looking into “Fail Fast vs Fail Safe” we should aware of the term “Concurrent Modification”

What is Concurrent Modification ?

Is nothing but one or more threads try modify the structure of the collection
(i.e adding or deleting or updating element to collection) parallelly is know as Concurrent Modification.

 

Fail Fast Iterator Example 

Fail fast Iterator throws Concurrent Modification Exception if there is

structural modification of the collection while iterating the collection.see the below example

 

when we try to add “Ravi ” to collection we get below exception.

 

Fail SafeIterator Example

Fail safe Iterator will not throws Concurrent Modification Exception if there is
structural modification of the collection while iterating the collection.see the below example

But here if you try to add “Ravi ” to collection we will not get any exception.

OUT PUT:

 

 

 

 

Posted in InterviewQuestions and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">