gpt4 book ai didi

java - 在外部修改时流式传输并发集合是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:31 25 4
gpt4 key购买 nike

我有一个被多个线程访问的 ConcurrentLinkedQueue;其中的对象是不可变的。在一个线程中,我需要数据的快照,这是通过调用 stream 来实现的。安全吗?我知道 non-interference要求,但它似乎是在谈论对流操作之一的修改(“源可能不是并发的流管道永远不应该修改流的数据源”),不一定是外部的。此外,ConcurrentLinkedQueue 是为并发访问而设计的,所以就是这样。

最佳答案

来自您提供的链接中的文档

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose Spliterator reports the CONCURRENT characteristic

来自 SplitIterator 的文档(其 CONCURRENT 特性)

static final int 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.

这是 Collection 接口(interface)流方法的实现(在 ConcurrentLinkedQueue 中没有被覆盖)

default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}

只要 ConcurrentLinkedQueue 使用 CONCURRENT SplitIterator(确实如此),我就假设您可以使用 stream() 安全地迭代您的 ConcurrentLinkedQueue。

关于java - 在外部修改时流式传输并发集合是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755361/

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