What is the logic of the failover iterator?

If a fail-safe iterator creates a separate copy and works on it, then how does he know any changes made to the original?

public class concurrentHashMap { public static void main(String[] args) throws InterruptedException { MapCheck obj1 = new MapCheck(); Thread t1 = new Thread(new Runnable() { @Override public void run() { obj1.put(); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { obj1.iterte(); } }); t1.start(); t2.start(); t1.join(); t2.join(); } } class MapCheck { Map<Integer,String> map = new ConcurrentHashMap<>(); { map.put(1, "pujan"); map.put(2, "manish"); map.put(3, "swati"); } void iterte() throws InterruptedException { for (int key : map.keySet()) { Thread.sleep(2000); System.out.println(map.get(key)); } } void put() throws InterruptedException{ Thread.sleep(2000); map.put(1, "pujan1"); map.put(2, "manish1"); map.put(3, "swati1"); } } 

Output:

 pujan1 manish1 swati1 
+8
java iterator collections
Jul 13 '16 at 0:59
source share
1 answer

In Java there is no such thing as a “fail-safe” iterator. At least Java SE specifications do not define such a term. Therefore, I recommend that you do not use the term "fail-safe" to describe Java iterators.

I am well aware that various articles on the Internet and elsewhere in Qaru use the term "fail-safe", but their use is not final, and it may be incorrect or at least misleading. I believe that you were misled by such documentation.

It seems like you read somewhere that the iterator with the "fault tolerant" works on a separate copy. In your example, you are using ConcurrentHashMap , which does have iterators that do not work fast. However, CHM iterators do not work with copy. Instead, they have semantics that are described by the official specification as weakly consistent . The definition is somewhat abstruse, but essentially, any element reported by such an iterator is guaranteed to exist in the collection at some point in time. These iterators may or may not reflect changes to the collection that were made after the start of the iteration. This is why the thread that starts the iterator sees the changes made by another thread. (It is also possible that some or none of the changes is not visible, as these streams have a data race.)

An example of another collection whose iterators do not work fast is CopyOnWriteArrayList . These collection iterators work with a snapshot, so any subsequent changes to the collection are never displayed through the iterator.

For completeness, here is the definition of the fail-fast iterator from the ArrayList specification. Most other (non-competitive) collections in Java have fast iteration tactics that have been defined similarly.

+12
Jul 13 '16 at 2:54 on
source share



All Articles