gpt4 book ai didi

java - 在迭代 ConcurrentHashMap 时添加和删除值

转载 作者:行者123 更新时间:2023-12-01 07:20:09 24 4
gpt4 key购买 nike

我有这个代码:

private ConcurrentMap<String, Integer> myMap = new ConcurrentHashMap<>();

@Scheduled(fixedDelay = 600_000)
public void foo(){
myMap.values().stream().
filter(predicate()).
forEach(this::remove);
}

public void insert(String str, Integer value){
myMap.put(str, value);
}

如果在迭代此映射时,有人会在其中添加新值或从中删除现有值,会发生什么情况?

最佳答案

ConcurrentHashMap 的文档有一些关于行为的细节。首先我们看看什么 ConcurrentHashMap.values() 是:

Returns a Collection view of the values contained in this map...

The view's iterators and spliterators are weakly consistent.

The view's spliterator reports Spliterator.CONCURRENT and Spliterator.NONNULL.

有趣的是术语 "weakly consistent" Spliterator.CONCURRENT ,其中前者描述为:

Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators and Spliterators provide weakly consistent rather than fast-fail traversal:

  • they may proceed concurrently with other operations
  • they will never throw ConcurrentModificationException
  • 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.

Spliterator.CONCURRENT 描述为:

Characteristic value signifying that the element source may be safely concurrently modified (allowing additions, replacements, and/or removals) by multiple threads without external synchronization. If so, the Spliterator is expected to have a documented policy concerning the impact of modifications during traversal.

从所有这些文档中,并与 ConcurrentHashMap 的并发模型保持一致,这意味着流管道是完全线程安全的,并且将遍历创建迭代器时存在的元素。

关于java - 在迭代 ConcurrentHashMap 时添加和删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41449761/

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