gpt4 book ai didi

java-8 - Spliterator:线程安全与否?

转载 作者:行者123 更新时间:2023-12-01 09:47:36 26 4
gpt4 key购买 nike

我正在查看 Spliterator 的文档,根据它,Spliterator 不是线程安全的:

Despite their obvious utility in parallel algorithms, spliterators are not expected to be thread-safe; instead, implementations of parallel algorithms using spliterators should ensure that the spliterator is only used by one thread at a time. This is generally easy to attain via serial thread-confinement, which often is a natural consequence of typical parallel algorithms that work by recursive decomposition.

但是,在其进一步的文档中,陈述了与上述声明相矛盾的声明:

Structural interference of a source can be managed in the following ways (in approximate order of decreasing desirability):

The source manages concurrent modifications.For example, a key set of a java.util.concurrent.ConcurrentHashMap is a concurrent source. A Spliterator created from the source reports a characteristic of CONCURRENT.

那么这是否意味着从线程安全集合生成的 Spliterator 将是线程安全的?对吗?

最佳答案

不,报告 CONCURRENT 特性的 Spliterator 将具有线程安全的 source,这意味着即使在源同时被修改。但是 Spliterator 本身可能仍然具有不能同时操作的状态。

请注意,您的引用源于对“如何管理源的结构干扰”的描述,而不是关于拆分器的一般行为。

这也在 documentation of the CONCURRENT characteristic itself 中提供:

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.

没有别的。

因此,这些特征的后果小得惊人。报告 CONCURRENTIMMUTABLESpliterator 永远不会抛出 ConcurrentModificationException,仅此而已。在所有其他方面,Stream API 无法识别这些特征之间的差异,因为 Stream API 从不执行任何源操作,事实上,它不会实际上知道来源(除了间接通过 Spliterator),所以它无法进行此类操作,也无法检测是否发生了并发修改。

关于java-8 - Spliterator:线程安全与否?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45458031/

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