Java 8 中的 parallelStream 中产生了多少线程? [英] How many threads are spawned in parallelStream in Java 8?

查看:78
本文介绍了Java 8 中的 parallelStream 中产生了多少线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JDK8 中,当我使用 parallelStream 时会产生多少线程?例如,在代码中:

In JDK8, how many threads are spawned when i'm using parallelStream? For instance, in the code:

list.parallelStream().forEach(/** Do Something */);

如果这个列表有 100000 个项目,会产生多少线程?

If this list has 100000 items, how many threads will be spawned?

此外,每个线程都获得相同数量的项目来处理还是随机分配?

Also, do each of the threads get the same number of items to work on or is it randomly allotted?

推荐答案

Oracle 的并行流实现[1] 使用当前线程,此外,如果需要,还使用组成默认 fork 连接池的线程 ForkJoinPool.commonPool(),它的默认大小等于您的 CPU 内核数少 1.

The Oracle's implementation[1] of parallel stream uses the current thread and in addition to that, if needed, also the threads that compose the default fork join pool ForkJoinPool.commonPool(), which has a default size equal to one less than the number of cores of your CPU.

可以使用此属性更改公共池的默认大小:

That default size of the common pool can be changed with this property:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=8

或者,您可以使用自己的池:

Alternatively, you can use your own pool:

ForkJoinPool myPool = new ForkJoinPool(8);
myPool.submit(() ->
    list.parallelStream().forEach(/* Do Something */);
).get();

关于顺序,只要有线程可用,作业就会被执行,没有特定的顺序.

Regarding the order, jobs will be executed as soon as a thread is available, in no specific order.

正如@Holger 正确指出的,这是一个特定于实现的细节(只有 文档底部的一个模糊参考),这两种方法都适用于 Oracle 的 JVM,但绝对不能保证适用于其他供应商的 JVM,该属性不能存在于非 Oracle 实现和 Streams 中甚至无法使用 ForkJoinPool 在内部呈现基于 ForkJoinTask.fork 行为的替代方案完全无用(参见此处 了解详情.

As correctly pointed out by @Holger this is an implementation specific detail (with just one vague reference at the bottom of a document), both approaches will work on Oracle's JVM but are definitely not guaranteed to work on JVMs from other vendors, the property could not exist in a non-Oracle implementation and Streams could not even use a ForkJoinPool internally rendering the alternative based on the behavior of ForkJoinTask.fork completely useless (see here for details on this).

这篇关于Java 8 中的 parallelStream 中产生了多少线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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