Thread-local storage

Recently, I spent some time to find information how actually “thread local” variables are working. To understand topic in high level, it is useful to read Wikipedia page about this topic:

From article we know, that the idea is quite simple: we just use static or global memory local to a thread, so every thread has his own piece of memory world when we could store such variables. Below you could find sample from ThreadLocal<T> documentation page, which just generates unique identifiers per thread:

import java.util.concurrent.atomic.AtomicInteger;

 public class UniqueThreadIdGenerator {

     private static final AtomicInteger uniqueId = new AtomicInteger(0);

     private static final ThreadLocal < Integer > uniqueNum =
         new ThreadLocal < Integer > () {
             @Override protected Integer initialValue() {
                 return uniqueId.getAndIncrement();

     public static int getCurrentThreadId() {
         return uniqueId.get();
 } // UniqueThreadIdGenerator

But actually, how is that happen that java ThreadLocal class is able to use Thread-local storage? Quite good answer could be found (as always) on stack overflow:

If you are eager to know even more details, take a look on ThreadLocal source code: + Thread source code:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s