Monday, July 16, 2018

Can you write code for the implementation of Fail Safe Iteration in java?

Problem statement: how do you write code for Fail Safe Iteration in java?
#ConcurrentHashMap:
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
public class FailSafeExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap        
       ConcurrentHashMap<String, Integer> map
                = new ConcurrentHashMap<String, Integer>();
        map.put("ONE", 1);
        map.put("TWO", 2);
        map.put("THREE", 3);
        map.put("FOUR", 4);
        // Getting an Iterator from map        
       Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            System.out.println(key + " : " + map.get(key));
            // This will reflect in iterator.            
           // Hence, it has not created separate copy            
           map.put("SEVEN", 7);
        }
    }
}
Output:
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
SEVEN : 7

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...