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.62k stars 1.69k forks source link

请问下,在spring boot 场景下,filter 中进入时set ,但是业务中异步线程还未执行完,filter 请求已经finally remove了,这时获取到的值为null, 这种情况如何保证正确性 #641

Closed freshgeek closed 5 months ago

freshgeek commented 5 months ago

请问下,在spring boot 场景下,filter 中进入时set ,但是业务中异步线程还未执行完,filter 请求已经finally remove了,这时获取到的值为null, 这种情况如何保证正确性

oldratlee commented 5 months ago

对于TTL本身逻辑/功能, 主线程的修改(filter请求的remove)不会影响 给子任务传递了的值。

一般是因为ThreadLocal的值使用了共享的集合(如Map),所以修改子任务可见。可以看看: @freshgeek

这个TTL使用方式/问题的解决方法,可以看看:

更多可以看看:

freshgeek commented 5 months ago

TransmittableThreadLocal数据丢失问题 https://juejin.cn/post/7311500203432575026

oldratlee commented 5 months ago

TransmittableThreadLocal数据丢失问题 https://juejin.cn/post/7311500203432575026

executor.setTaskDecorator(runnable -> TtlRunnable.get(runnable, true));

// 推荐改成

executor.setTaskDecorator(TtlRunnable::get);

// 以避免不能在线程池中运行(可能)多次重复运行的任务