java - ConcurrentHashMap 的迭代器给出奇怪的结果

标签 java collections concurrency

ConcurrentHashMap 是线程安全的。因此,如果在迭代时向 map 添加任何值,则不应考虑它们。下面是我的代码:

public class Test {
public static void main(String[] args) {
    ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
    map.put("ONE", 1);
    map.put("TWO", 2);
    Iterator<String> it = map.keySet().iterator();
    while (it.hasNext()) {
        String key = (String) it.next();
        System.out.println(key + " : " + map.get(key));
        map.put("9", 10); // This should not be reflected in the Iterator
        map.put("5", 10); // This should not be reflected in the Iterator
    }
}
}

输出:

    TWO : 2
    ONE : 1
    9 : 10

我的问题是为什么迭代器考虑 map.put("9", 10);

最佳答案

ConcurrentHashMap is thread safe. So if am adding any values to map at the time of iterating, it should not consider them.

这是不正确的。这就是javadoc说:

"Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration."

注意“或自”!

它还说迭代器是“弱一致的”,这意味着:

"they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction."


简而言之,您期望 javadoc 显然没有说它们具有的迭代器属性。

关于java - ConcurrentHashMap 的迭代器给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439073/

相关文章:

java - 如何从匿名类中调用方法

java - 在 Collection<?超T>

java - 基于多连接的ArrayList排序

c++ - 防止并发使用和释放

java - 满足高并发时的简单web服务器

java - Maven clean 命令 : java. util.Collections.UnmodifiableRandomAccessList 到 java.util.ArrayList 类型的属性

java - 为什么这段代码不抛出 NullPointerException

java - 双重嵌套for循环迭代(ArrayList)

java - Spring boot JPA 获取列表并向其中添加项目会引发错误

java - 对于大型 ByteBuffer,单独 SocketChannel 的并发 read() 速度较慢