加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:40:04 所属栏目:Java 来源:网络整理
导读:我正在查看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 e
我正在查看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),所以它无法进行此类操作,也无法检测是否发生了并发修改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读