Reputation: 916
I was working on analyzing fail-safe iterators with Maps and verifying, if we are updating the keyset, will the operation happen on the clone or the actual map
private static void failSafeIterator() {
ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>();
map.put("a", "one");
map.put("b", "two");
Iterator<String> keyIterator=map.keySet().iterator();
while(keyIterator.hasNext()){
String key=keyIterator.next();
System.out.println(key+":"+map.get(key));
map.put("c", "three");
map.put("q", "four");
map.put("W", "five");
}
System.out.println(map.get("q"));
}
As per the above code snippet,
the addition of c,q and w should have happened on the clone and not on the actual collection
But i can see the update happening over the collection.
Also the output is a bit confusing as not all the key value pairs are printed, even though the key is present in the map.
Output:
a:one
b:two
c:three
W:five
four
Upvotes: 2
Views: 138
Reputation: 120938
The problem here is that you don't understand what weakly consistent iterator stands for, when using keySet().iterator()
, specifically this part of the documentation:
they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.
Imagine a case like this: you are iterating a ConcurrentHashMap
and printing whatever it has. Once you have seen a certain bucket and showed all of it's elements, you move to the next one, also updating the (suppose you add a key-value
pair to it) previous one. Updates to that previous one are not going to be shown, although they do exist.
After your loop, you can do :
System.out.println(map);
And see that everything is now present.
Upvotes: 2