Java 迭代 ConcurrentHashMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21025738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:02:53  来源:igfitidea点击:

Iterating over ConcurrentHashMap

javaconcurrency

提问by KCS

I referred many links regarding Iterator of ConcurrentHashMap, like Is iterating ConcurrentHashMap values thread safe?or any other on Google, even java doc,yet i am not much getting what kind of behavior i might face while iterating the Concurrenthashmap and simultaneously modifying it

我提到了很多关于 ConcurrentHashMap 迭代器的链接,比如迭代 ConcurrentHashMap 值线程安全吗?或谷歌上的任何其他人,甚至是 java doc,但我不太了解在迭代 Concurrenthashmap 并同时修改它时可能会面临什么样的行为

回答by Markus Malkusch

Read the JavaDoc for ConcurrentHashMap.values():

阅读 JavaDoc 以了解ConcurrentHashMap.values()

The view's iterator [..] guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

视图的迭代器 [..] 保证遍历构建迭代器时存在的元素,并且可能(但不保证)反映构建后的任何修改。

If you're interested in the contract of the other iterators, they have documentation as well.

如果您对其他迭代器的合同感兴趣,他们也有文档。

回答by Evgeniy Dorofeev

Yes, unlike regular maps you can iterate over ConcurrentHashMap and remove elements using Map.remove(key). Try this test

是的,与常规映射不同,您可以迭代 ConcurrentHashMap 并使用 Map.remove(key) 删除元素。试试这个测试

    ConcurrentHashMap<Integer, Integer> m = new ConcurrentHashMap<>();
    m.put(1, 1);
    m.put(2, 2);
    m.put(3, 3);
    for (int i : m.keySet()) {
        if (i == 2) {
            m.remove(i);
        }
    }
    System.out.println(m);

it prints

它打印

{1=1, 3=3}