我正在查看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将具有线程安全源,这意味着即使源同时被修改,它也可以安全地迭代它.但是,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.
没有其他的.
所以这些特征的后果是惊人的小.报告CONCURRENT或IMMUTABLE的Spliterator永远不会抛出ConcurrentModificationException,就是这样.在所有其他方面,Stream API不会识别这些特性之间的差异,因为Stream API从不执行任何源操作,事实上,它实际上并不知道源(除了间接通过Spliterator),所以它无法进行此类操作,也无法检测是否发生了并发修改.