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

使用`TransmittableThreadLocal<HashMap>`出现`ConcurrentModificationException` #677

Closed luocunhao closed 1 month ago

luocunhao commented 1 month ago
InheritableThreadLocal<Map<String, String>> logTagsLocal = TransmittableThreadLocal.withInitial(HashMap::new);

TtlExecutors.getTtlExecutorService(
            ExecutorServiceMgr.getExecutorService("esThreadPool",
                    ExecutorServiceMgr.CALLER_RUNS_HANDLER));

子线程不是会对父线程的HashMap做一份快照拷贝吗,那么即使子线程有修改map也不会影响父线程访问才对

oldratlee commented 1 month ago

@luocunhao

可以看看使用withInitialAndCopier(Supplier supplier, TtlCopier copierForChildValueAndCopy)方法:

InheritableThreadLocal<Map<String, String>> logTagsLocal =
  TransmittableThreadLocal.withInitialAndCopier(HashMap::new, HashMap::new);

PS:具体合适的解决方法与你需求相关。

更多说明参见已有issue: