Log4j2 ThreadContext映射不适用于parallelStream()

时间:2018-04-05 15:09:12

标签: java concurrency java-8 log4j log4j2

我有以下示例代码:

public class Test {
    static {
        System.setProperty("isThreadContextMapInheritable", "true");
    }

    private static final Logger LOGGER = LogManager.getLogger(Test.class);

    public static void main(String[] args) {
        ThreadContext.put("UUID", UUID.randomUUID().toString());
        LOGGER.info("in main method start");
        new Test().run();
        LOGGER.info("in main method end");    
    }

    private void run() {
        Collections.nCopies(10, 1)
                .parallelStream()
                .forEach(i->LOGGER.info("Inside thread"));    
    }
}

Log4j2模式如下:

<pattern>%X{UUID} [%t] %msg %n</pattern>

在上面运行产生结果:

2cf774ff-03c8-483e-9828-451b61349221 [main] in main method start 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [ForkJoinPool.commonPool-worker-3] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-3] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] in main method end 

如您所见,第一次记录[ForkJoinPool.commonPool-worker-1][ForkJoinPool.commonPool-worker-3]个帖子UUID变量,但其他时间未记录。

为什么Log4j2为某些线程跳过ThreadContext变量以及如何解决这个问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我知道这是旧帖子,
但是我在同一个问题上苦苦挣扎,花了几天的时间才找到可行的解决方案。
这是answer,创建自定义ThreadPoolExecutor确实解决了我的问题。