CommonPool中的ParallelStream队列任务,而不是自定义池

时间:2018-10-16 13:07:24

标签: java java-8 threadpool mdc forkjoinpool

我想对parallelStream使用自定义ThreadPool。原因是我想在任务中使用MDCContext。这是我使用自定义ThreadPool编写的代码:

final ExecutorService mdcPool = MDCExecutors.newCachedThreadPool();
mdcPool.submit(() -> ruleset.getOperationList().parallelStream().forEach(operation -> {
                log.info("Sample log line");
});

当MDC上下文未复制到任务时,我查看了日志。这些是我发现的日志。第一个日志在“(pool-16-thread-1)”中执行,但其他任务正在“ ForkJoinPool.commonPool-worker”上执行。第一个日志还具有MdcContextID。但是当我使用自定义ThreadPool提交任务时,所有任务都应在自定义ThreadPool中执行。

16 Oct 2018 12:46:58,298 [INFO] 8fcfa6ee-d141-11e8-b84a-7da6cd73aa0b (pool-16-thread-1) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,298 [INFO]  (ForkJoinPool.commonPool-worker-11) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,298 [INFO]  (ForkJoinPool.commonPool-worker-4) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,298 [INFO]  (ForkJoinPool.commonPool-worker-13) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,298 [INFO]  (ForkJoinPool.commonPool-worker-9) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,299 [INFO]  (ForkJoinPool.commonPool-worker-2) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line
16 Oct 2018 12:46:58,299 [INFO]  (ForkJoinPool.commonPool-worker-15) com.amazon.rss.activity.business.VariablesEvaluator: Sample log line

这是应该发生的还是我错过了什么?

1 个答案:

答案 0 :(得分:2)

不支持在自定义线程池中运行并行流。当在不同的Fork / Join池的工作线程中启动操作时,可能在不同的Fork / Join池中执行,但这似乎不是计划的功能,例如Stream然后,在某些操作中,实现代码仍将在内部使用公共池的工件。

在您的情况下,似乎ExecutorService返回的MDCExecutors.newCachedThreadPool()不是Fork / Join池,因此它根本没有表现出这种未记录的行为。

有一个功能请求JDK-8032512,涉及更多线程控制。据我所知,它是开放的,没有太多活动。