在Java 8中并行生成了多少个线程? [英] How many threads are spawned in parallelStream in Java 8?

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

问题描述

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

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

如果此列表包含100000个项目,将生成多少个线程?



另外,每个线程都可以获得相同数量的项目,还是随机分配?

解决方案

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



可以更改公共池的默认大小这个属性:

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

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

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

关于订单,只要线程可用,就会立即执行作业,而不是特定的顺序。



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


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

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

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?

解决方案

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.

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中并行生成了多少个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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