问题
Here is my test for ConcurrentHashMap
@Test
public void testIt2() {
Map<String, String> map = new ConcurrentHashMap<String, String>();
map.put("2", "2");
map.put("1", "1");
for (Entry<String, String> entry : map.entrySet()) {
map.clear();
System.out.println(entry.getKey());
}
}
the output is :
1
2
why?
回答1:
You can see the changes after the loop ends. You could print out the map again to see the difference. It will be empty. I would like to add a part of @waldheinz's answer:
What happens if you put or remove a value from the map while iterating it?
It is guaranteed that things will not break if you do this (that's part of what the "concurrent" in
ConcurrentHashMap
means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of its creation. Further changes may be reflected in the iterator, but they do not have to be.
来源:https://stackoverflow.com/questions/38473072/clear-elements-from-concurrenthashmap-while-iterating