views:

1009

answers:

4

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?

+1  A: 

I think you are referring to ThreadLocal?

Source is here.

Michael Sharek
+4  A: 

ThreadLocal variables in Java works by accessing a HashMap held by the Thread.currentThread() instance.

Christian Vest Hansen
+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
So, it incurs no locks or contention, right?
ripper234
I can't see why any should be needed, given that by definition the data is only visible to a single thread.
skaffman
Correct, there's no synchronisation or locking around or within the ThreadLocalMap, as it's only accessed in-thread.
Cowan
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
Not really an answer to the question.. the asker understands what they are, and wants to know the implementation, not the usage.
Cowan