美文网首页
Tomcat中的CompletableFuture里获取Cont

Tomcat中的CompletableFuture里获取Cont

作者: 梅肯羅斯 | 来源:发表于2020-03-18 22:02 被阅读0次
    CompletableFuture.runAsync(() -> doSomething());
    

    在doSomething()中调用Thread.currentThread().getContextClassLoader()时返回null。
    使用Stream.parallel()也会出现此现象。

    原因:

    (https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8184335) JDK9后修复

    In Java SE 9, threads that are part of the fork/join common pool will always return the system class loader as their thread context class loader. In previous releases, the thread context class loader may have been inherited from whatever thread causes the creation of the fork/join common pool thread, e.g. by submitting a task. An application cannot reliably depend on when, or how, threads are created by the fork/join common pool, and as such cannot reliably depend on a custom defined class loader to be set as the thread context class loader.

    在Java9中,fork/join common pool会始终返回系统类加载器作为上下文类加载器。而之前的版本上下文类加载器可能从触发fork/join common pool创建的线程继承而来。

    好吧 看来common pool返回null才是期望的。(这里的common pool 指的就是ForkJoinCommonPool)

    此外,使用ForkJoinPool还会导致内存泄漏TestCase
    Tomcat 8.5.11 版本后修复:扩展JreMemoryLeakPreventionListener 防止内存泄漏

    解决方案

    • 使用自定义线程池
    CompletableFuture.runAsync(() -> doSomething(), myExecutor);
    
    • 如果非要使用ForkJoinPool,那么就自己创建一个
    ForkJoinPool forkJoinPool = new ForkJoinPool(NUM);
    forkJoinPool.execute(() -> doSomeThing());
    

    相关文章

      网友评论

          本文标题:Tomcat中的CompletableFuture里获取Cont

          本文链接:https://www.haomeiwen.com/subject/aaacyhtx.html