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

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...