本文介绍了迭代时清除ConcurrentHashMap中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我对ConcurrentHashMap的测试

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());
    }
}

输出为:

1
2

为什么?

推荐答案

循环结束后,您可以看到更改.您可以再次打印出地图以查看差异.它是空的.我想添加 @waldheinz 的:

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:

如果执行此操作,则可以确保不会中断(这是ConcurrentHashMap中并发"含义的一部分).但是,不能保证一个线程会看到另一线程执行的映射更改(无需从映射中获取新的迭代器).保证迭代器在创建地图时能够反映其状态.进一步的更改可能会反映在迭代器中,但不一定如此.

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.

这篇关于迭代时清除ConcurrentHashMap中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:18