Spliterator:线程安全与否?

Spliterator: Thread-Safe or not?

我正在查看 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,这意味着它可以安全地迭代它,即使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.

没有别的。

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