If you see this image, you would find that I have just changed the keys and I found surprisingly two different results. In left hand side I found four strings as output while in right hand side only three strings as output. Can some one make me understand this difference.
-
Show code, output and/or possible error messages as properly formatted text in the question, not as image or by external link. – Michael Butscher Oct 26 '18 at 14:12
2 Answers
ConcurrentHashMap.iterator() doesn't guarantee you will or won't see an entry added while iterating over it. There is an internal order it passes over the entries and if you add before the point it is up to you won't see the entry.
If you iterate over the values again you should see that in the second it was before the first entry.

- 525,659
- 79
- 751
- 1,130
There is probably a reason that you used ConsurrentHashMap
instead of a regular Map
implementation like HashMap
. If you try to use one of this implementations and run your code you will notice a ConcurrentModificationException
, which can be thrown whenever you update a HashMap
while iterating over it. If you change that implementation to ConcurrentHashMap
this will change the following:
A hash table supporting full concurrency of retrievals and high expected concurrency for updates. [...] Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset.
So, concurrent updates are permitted while you iterate over the Map
. Now, the question if you can actually see the value or not can be related to the iteration order of the Map
implementation (which can change between Java version, as there generally is no iteration order in a Map
). If the element is inserted before the current iteration, it won´t be iterated over. If the element is inserted after, it prints out on the console. After all, you should not rely on it.
However, if you loop over the Map
again
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
System.out.println(map.get(it.next()));
}
you will correctly see the value in the output:
iPhone
HTC one
S5
Xperia Z <<< here it is
iPhone
HTC one
S5
That the previous assumption is correct can now be proven, since the key "Sony" has been iterated over first, so it won´t show up in the previous iteration. If you compare this to you first try, the key "d" has been iterated over last, so it shows up on the console. To be exact, if you have a value that is iterated over and not the first value, it will show up (since you add it already at the second iteration).
However, as previously said, keep in mind that iteration order may change between Java versions and that this could just apply for your concrete example.

- 2,773
- 3
- 16
- 30