Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Context:

static ThreadLocal<MyType> threadLocalMyType = ...

What i'd like is to say something like:

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...]
}
like image 602
Jonas N Avatar asked May 08 '10 20:05

Jonas N


People also ask

How does ThreadLocal work in Java?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

What is valid about ThreadLocal?

Java ThreadLocal class provides thread-local variables. It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.

Are ThreadLocal variables thread safe?

Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.

Does ThreadLocal have to be static?

ThreadLocal s should be stored in static variables to avoid memory leaks. If a ThreadLocal is stored in an instance (non-static) variable, there will be M \* N instances of the ThreadLocal value where M is the number of threads, and N is the number of instances of the containing class.


1 Answers

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.

like image 195
Bozho Avatar answered Sep 28 '22 04:09

Bozho