-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
请教个问题:TransmittableThreadLocal中的holder为什么不使用ThreadLocal #132
Comments
还有个问题: @Override
public void run() {
Object captured = capturedRef.get();
if (captured == null || releaseTtlValueReferenceAfterRun && !capturedRef.compareAndSet(captured, null)) {
throw new IllegalStateException("TTL value reference is released after run!");
}
Object backup = replay(captured);
try {
runnable.run();
} finally {
restore(backup);
}
} 从这段代码中可以看出,task所在线程每次使用的threadlocal都是从 |
直接给复现问题的测试Case如下, @yearyeardiff 你可以试试 :) 期望输出 import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo {
public static void main(String[] args) throws Exception {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final TransmittableThreadLocal<String> ttl = new TransmittableThreadLocal<>();
ttl.set("hello");
executorService.submit(TtlRunnable.get(() -> System.out.println(ttl.get())));
Thread.sleep(500);
new Thread( () -> {
// 在new线程中,执行线程池操作
final TtlRunnable task = TtlRunnable.get(() -> System.out.println(ttl.get()));
executorService.submit(task);
}).start();
Thread.sleep(500);
}
} PS这个问题 提过Bug 并 修复发版,更多信息 参见 Issue #70 嵌入Thread调用的bug |
另外,推荐看一下 Issue |
懂了,之前的理解是因为没有考虑到下面的场景。 new Thread( () -> {
// 在new线程中,执行线程池操作
final TtlRunnable task = TtlRunnable.get(() -> System.out.println(ttl.get()));
executorService.submit(task);
}).start(); 解答很详细,感谢! |
我对holder的理解是:保存当前线程所有的threadlocal用于在
TtlRunnable.get(task)
生成快照。个人觉得没有必要从使用InheritableThreadLocal类型的holder从父线程中继承,完全可以从生成的快照中恢复到holder中The text was updated successfully, but these errors were encountered: