How is Java's ThreadLocal implemented under the hood?

Viewed 15909

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?

5 Answers

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.

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

Related