gpt4 book ai didi

java - concurrentMap.keySet().toArray() 线程安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:05:29 24 4
gpt4 key购买 nike

我有一个 ConcurrentHashMap<String, Object> concurrentMap;

我需要返回带有 map 键的 String[]。

是下面的代码:

  public String[] listKeys() {
return (String[]) concurrentMap.keySet().toArray();
}

线程安全吗?

最佳答案

虽然 ConcurrentHashMap 是线程安全的类,但在键上使用的 Iterator不确定与任何后续 HashMap 更改同步,一旦创建...

来自spec :

    public Set<K> keySet()

Returns a Set view of the keys contained in this map......
...........................

The view's iterator is a "weakly consistent" iterator that will
never throw ConcurrentModificationException, and 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.

关于java - concurrentMap.keySet().toArray() 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com