本文翻译自:Custom thread pool in Java 8 parallel stream
Is it possible to specify a custom thread pool for Java 8 parallel stream ? 是否可以为Java 8 并行流指定自定义线程池? I can not find it anywhere. 我在任何地方都找不到。
Imagine that I have a server application and I would like to use parallel streams. 假设我有一个服务器应用程序,并且想使用并行流。 But the application is large and multi-threaded so I want to compartmentalize it. 但是应用程序很大且是多线程的,所以我想将其划分。 I do not want a slow running task in one module of the applicationblock tasks from another module. 我不希望一个模块中的一个模块中的某个模块运行缓慢,而另一个模块中的任务却运行缓慢。
If I can not use different thread pools for different modules, it means I can not safely use parallel streams in most of real world situations. 如果不能为不同的模块使用不同的线程池,则意味着在大多数实际情况下,我不能安全地使用并行流。
Try the following example. 请尝试以下示例。 There are some CPU intensive tasks executed in separate threads. 在单独的线程中执行一些CPU密集型任务。 The tasks leverage parallel streams. 任务利用并行流。 The first task is broken, so each step takes 1 second (simulated by thread sleep). 第一项任务已中断,因此每个步骤需要1秒钟(由线程睡眠模拟)。 The issue is that other threads get stuck and wait for the broken task to finish. 问题是其他线程被卡住并等待中断的任务完成。 This is contrived example, but imagine a servlet app and someone submitting a long running task to the shared fork join pool. 这是一个人为的示例,但请想象一个servlet应用程序,有人向共享的fork联接池提交了长时间运行的任务。
public class ParallelTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newCachedThreadPool();
es.execute(() -> runTask(1000)); //incorrect task
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.shutdown();
es.awaitTermination(60, TimeUnit.SECONDS);
}
private static void runTask(int delay) {
range(1, 1_000_000).parallel().filter(ParallelTes