How is ThreadLocal implemented? Is it implemented in Java (using some concurrent map from ThreadID to object), or does it use some JVM hook to do it more efficiently?
+4
A:
ThreadLocal variables in Java works by accessing a HashMap held by the Thread.currentThread() instance.
Christian Vest Hansen
2009-07-29 19:20:58
+16
A:
You mean java.lang.ThreadLocal
. It's quite simple, really, it's just a Map of name-value pairs stored inside each Thread
object (see the Thread.threadLocals
field). The API hides that implementation detail, but that's more or less all there is to it.
skaffman
2009-07-29 19:20:58
So, it incurs no locks or contention, right?
ripper234
2009-07-30 06:16:43
I can't see why any should be needed, given that by definition the data is only visible to a single thread.
skaffman
2009-07-30 07:14:28
Correct, there's no synchronisation or locking around or within the ThreadLocalMap, as it's only accessed in-thread.
Cowan
2009-07-30 07:31:50
A:
Here is a good example for using TLS (thead-local-storage) variables in Java.
public class Main { public static void main(String[] argv) throws Exception { ThreadLocal localThread = new ThreadLocal(); Object o = localThread.get(); localThread.set(o); } }
Janaka
2009-07-30 09:42:37
Not really an answer to the question.. the asker understands what they are, and wants to know the implementation, not the usage.
Cowan
2009-07-30 23:15:31