alibaba / transmittable-thread-local

📌 a missing Java std lib(simple & 0-dependency) for framework/middleware, provide an enhanced InheritableThreadLocal that transmits values between threads even using thread pooling components.
https://github.com/alibaba/transmittable-thread-local
Apache License 2.0
7.66k stars 1.69k forks source link

嵌入Thread调用的bug #70

Closed aftersss closed 7 years ago

aftersss commented 7 years ago

运行以下代码:

final ExecutorService executorService = Executors.newSingleThreadExecutor();

final InheritableThreadLocal<String> tl1 = new TransmittableThreadLocal<>();

tl1.set("hello");

TtlRunnable runnable = TtlRunnable.get(new Runnable() {
    @Override
    public void run() {
        System.out.println("pool tl1:"+tl1.get());
    }
});
executorService.submit(runnable);
Thread.sleep(200);

new Thread(){
    public void run(){
        TtlRunnable runnable = TtlRunnable.get(new Runnable() {
            @Override
            public void run() {
                System.out.println("pool tl1-2:"+tl1.get());
            }
        },false,false);
        executorService.submit(runnable);
    }
}.start();

输出:

pool tl1:hello
pool tl1-2:null

第二行不应该为null,改成使用InheritableThreadLocal是正常的。

oldratlee commented 7 years ago

@aftersss 收到,我看看

oldratlee commented 7 years ago

@aftersss 修复在进行中。转成了复现问题的UT,参见提交: bbd4f9ea028e1f383585f61588598c55acd98c36

如果急着解决,先给一个bypass的方法:

new Thread(){
    public void run(){
        // 这里补一行 get
        tl1.get();

        TtlRunnable runnable = TtlRunnable.get(new Runnable() {
            @Override
            public void run() {
                System.out.println("pool tl1-2:"+tl1.get());
            }
        },false,false);
        executorService.submit(runnable);
    }
}.start();
oldratlee commented 7 years ago

问题已经修复,参见 提交

  1. c5ed61a64797eb2d9086a76fb8f068b195d5c667
  2. 87a02ab359493bf1bb3040bce17fe05ba01e08fb

发布了版本 2.1.0这里是release log, Maven依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>transmittable-thread-local</artifactId>
    <version>2.1.0</version>
</dependency>

@aftersss 非常赞 👍

嵌套ThreadExecutorServcie这样的使用方式, 之前的UT没有覆盖到,到现在为止的使用中也没有触发这个问题。

非常感谢你的问题反馈!!

aftersss commented 7 years ago

OK,谢谢

oldratlee commented 7 years ago

@aftersss 问一下你在什么场景/需求下使用ttl,哪个公司/项目。收集了解一下用户 :)