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

我想为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

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

解决方法:

不支持在自定义线程池中运行并行流.当在不同的Fork / Join池的工作线程中启动操作时,恰好在不同的Fork / Join池中执行它,但这似乎不是计划的功能,因为Stream实现代码仍将使用的工件那么在某些操作中内部的公共池.

在您的情况下,似乎MDCExecutors.newCachedThreadPool()返回的ExecutorService不是Fork / Join池,因此它根本不会显示此未记录的行为.

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

上一篇:什么是Java线程池RejectedExecutionHandler中传递的可运行对象


下一篇:java – Websphere中这些线程池有什么区别?