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

标签 java multithreading concurrency java-8 java-stream

我有一个被多个线程访问的 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/

相关文章:

c - 两个线程——从 STDIN 读取文本并通过管道发送

multithreading - Windows XP 上的线程

javascript - 由于异步回调,变量被覆盖

java - 从文本导入数据

关键系统的 java tomcat web 应用程序 war 更新

java - SQL 语句 ‘IN’ 包含太多表达式

multithreading - Win32 : ReadFileEx() on STD_IN_HANDLE blocks, 为什么?

python - 在 Python 中监控并发性(跨进程共享对象)

java - 线程本地删除方法

java - Json 反序列化 - 预期为 BEGIN_OBJECT,但结果为 STRING