Search code examples
javacollectionsconcurrenthashmap

Java : In ConcurrentHashMap , why is having differnet output if i changes the key


First iteration:-

class ConcurrentHashMapBehaviour
{       
    public static void main(String[] args) 
    {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
        map.put("ONE", 1);
        map.put("TWO", 2);
        map.put("THREE", 3);
        map.put("FOUR", 4);
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()){
            String key = (String) it.next();
            System.out.println(key+" : "+map.get(key));
            map.put("SEVEN", 7);
        }
    }
}

Output is :

ONE : 1
FOUR : 4
TWO : 2
THREE : 3
SEVEN : 7

Second Iteration after changing the key

class ConcurrentHashMapBehaviour
{       
    public static void main(String[] args) 
    {
        ConcurrentHashMap<String, Integer> map = new 
        ConcurrentHashMap<String, Integer>();

        map.put("ONE", 1);
        map.put("TWO", 2);
        map.put("THREE", 3);
        map.put("FOUR", 4);
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()){
            String key = (String) it.next();
            System.out.println(key+" : "+map.get(key));
            map.put("FIVE", 5);
        }           
    }
} 

Output is:

ONE : 1
FOUR : 4
TWO : 2
THREE : 3

So my question is why first iteration include the SEVEN as output but not FIVE in second iteration?


Solution

  • Javadoc (with my emphasis):

    Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.

    In other words, there are NO guarantees on the view available to the iterator. It may or may not be aware of changes to the map after the Iterator is created. The only guarantee is

    They do not throw ConcurrentModificationException.