简体   繁体   中英

Clear elements from ConcurrentHashMap while iterating

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM