PUNEET TIWARI
PUNEET TIWARI

Reputation: 3

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?

Upvotes: 0

Views: 63

Answers (2)

janssen-dev
janssen-dev

Reputation: 2771

When you type

Iterator<String> it = map.keySet().iterator();
while (it.hasNext())
{
    String key = it.next();
    System.out.println(key + " : " + map.get(key));
    map.put("FIVE", 5);
}

You might put ("FIVE", 5) to the map each time you print a value, but that doesn't add it to the running iterator. The iterator does not update. In fact, changing an iterating list or map without an iterator (for example with a for each-loop) would result in a ConcurrentModificationException.


When you do a second loop after your first and create a new iterator. It will also print out the new value:

Iterator<String> it2 = map.keySet().iterator();
while (it2.hasNext())
{
    String key = it2.next();
    System.out.println(key + " : " + map.get(key));
}

Output:

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

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

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.

Upvotes: 6

Related Questions