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...]
}
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.
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.
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.
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.
One way would be to handle this manually:
ThreadLocal
(extend it)static
) Map
of Threads and valuesAlternatively, with some reflection (getDeclaredMethod()
and setAccessible(true)
), you can:
Thread.getThreads()
yourThreadLocal.getMap(thread)
(for each of the above threads)map.getEntry(yourThreadLocal)
The 1st is more preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With