Clear elements from ConcurrentHashMap while iterating

泪湿孤枕 提交于 2019-12-12 20:06:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!