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

前端 未结 3 1224
执念已碎
执念已碎 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:47

    One way would be to handle this manually:

    • use a wrapper of ThreadLocal (extend it)
    • whenever a value is set, keep a (static) Map of Threads and values

    Alternatively, with some reflection (getDeclaredMethod() and setAccessible(true)), you can:

    • call Thread.getThreads()
    • call yourThreadLocal.getMap(thread) (for each of the above threads)
    • call map.getEntry(yourThreadLocal)

    The 1st is more preferable.

提交回复
热议问题