有没有办法迭代或复制Java ThreadLocal的所有值?

Jon*_*s N 4 java multithreading thread-local

语境:

static ThreadLocal<MyType> threadLocalMyType = ...
Run Code Online (Sandbox Code Playgroud)

我想要的是说:

for (ThreadLocalEntry e: threadLocalMyType.getMapLikeThing() {
    // Thread t = e.getKey(); 
    // I don't need the thread value right now, but it might be useful for 
    // something else. 

    MyType theMyType = e.getValue();
    // [...do something with theMyType...]
}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 6

一种方法是手动处理:

  • 使用包装ThreadLocal(扩展)
  • 每当设置一个值时,保留一个(static)Map线程和值

或者,通过一些反射(getDeclaredMethod()setAccessible(true)),您可以:

  • 呼叫 Thread.getThreads()
  • 调用yourThreadLocal.getMap(thread)(对于上述每个线程)
  • 呼叫 map.getEntry(yourThreadLocal)

第一个是更优选的.