Java 8并行流中的自定义线程池

本文翻译自: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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值