Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fail-fast iterator

I get this definition : As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun.

what it mean by since iteration has begun? is that mean after Iterator it=set.iterator() this line of code?

public static void customize(BufferedReader br) throws IOException{  
    Set<String> set=new HashSet<String>(); // Actual type parameter added  
    **Iterator it=set.iterator();**
like image 880
joy Avatar asked Dec 12 '22 20:12

joy


1 Answers

First of all, they are fail-fast, not fail-safe.

The contract is that structural modifications (i.e. insertions/deletions) of certain types of collections invalidate existing iterators into the collection. Fail-fast iterators attempt to detect that they are not supposed to be valid and throw a ConcurrentModificationException. This is done as a service to you, the programmer, to help discover this type of bugs quicker.

In your example:

Iterator it = set.iterator();
it.next();
set.add("unique-entry"); // invalidates the iterator
it.next();

If you're lucky, the second it.next() will detect the invalid usage and throw an exception. Note that this is done on a best-effort basis and is not guaranteed.

like image 78
NPE Avatar answered Jan 03 '23 03:01

NPE