Java 8流是原子的吗? [英] Is Java 8 streams atomic?

查看:106
本文介绍了Java 8流是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过一些帖子,但是,我仍然感到困惑。

I read a few posts, however, I'm still confused.

我知道并行流将以并行方式执行,这将利用CPU。并且我相信子作业将以原子单位执行,我是否正确?

I know that parallel streams will be executed in a parallel manner that will utilise the CPUs. and I believe that the sub jobs will be executed as atomic units, am I correct?

但是常规Java 8流呢?

But what about regular Java 8 streams?

如果我执行让我们说下一行代码:

If i execute let's say the next line of code:

users.stream().map(user->user.getUsername()).collect(Collectors.toList()); 

该行是否也将以线程安全/原子方式执行?

Will that line be executed in a thread-safe/atomic manner as well?

推荐答案

没有通用线程安全性或原子性这样的东西。对于访问同一变量的线程,原子字段更新只是原子的, synchronized 对于仅在同一实例上同步的线程,代码块是原子/线程安全的。

There is no such thing as general thread safety or atomicity. Atomic field updates are only atomic in respect to threads accessing the same variable, synchronized code blocks are executed atomic/thread safe in respect to threads synchronizing on the same instance only.

流操作本身就是纯粹的本地操作,即使对于并行流操作也是如此,因为参与该操作的线程与任何其他线程无关。如果您使用具有(非局部)副作用的函数,这是非常不鼓励的,则无法保证,这些副作用没有增加的线程安全性或原子性。唯一的例外是终端操作 forEach forEachOrdered ,它们用于产生副作用并且有关行为的详细记录多线程。

A stream operation in itself is a purely local operation, this holds even for parallel stream operations, as the threads participating in that operation are unrelated to any other threads. If you use functions with (non local) side effects, which is very discouraged, there are no guarantees, there's no added thread safety nor atomicity for these side effects. The only exception are the terminal operations forEach and forEachOrdered, which are intended for producing side effects and well documented regarding the behavior with multiple threads.

所以操作 users.stream()。map(user-> user.getUsername())。collect(收藏家) .toList()),假设方法 getUsername()遵循合同并且没有副作用,对任何其他线程都不可见所有。如果以线程安全的方式将返回的列表发布到其他线程,那么它将是安全的,如果你让它以不安全的方式逃脱,将无法保证。如果您从未将结果发布到其他线程,则问题变得无关紧要。

So the operation users.stream().map(user->user.getUsername()).collect(Collectors.toList()), assuming that the method getUsername() follows the contract and has no side effects, is not visible to any other thread at all. If you publish the returned list to other threads in a thread safe way, it will be safe, if you let it escape in an unsafe way, there will be no guarantees. If you never publish the result to other threads, the question becomes irrelevant.

这篇关于Java 8流是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆