Is there no way to iterate over or copy all the values of a Java ThreadLocal?

前端 未结 3 1226
执念已碎
执念已碎 2020-12-19 12:26

Context:

static ThreadLocal threadLocalMyType = ...

What i\'d like is to say something like:

for (ThreadLoc         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 12:50

    No, because internally it is implement differently: each thread has a map-like thing of its locals. What you want to do would be inherently thread-unsafe if ThreadLocal allowed it. Each thread obviously doesn't use any kind of synchronization when accessing its own locals: no other thread can do that, so synchronization is not needed. For this reason, accessing the locals map from any other thread (if that was possible) would be thread-unsafe.

    As Bozho suggested, you could do that by subclassing ThreadLocal and duplicating values somewhere else. Don't forget to synchronize access to that "somewhere else" properly.

提交回复
热议问题