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: http://en.wikipedia.org/wiki/Thread-local_storage.

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: http://stackoverflow.com/questions/1202444/how-is-javas-threadlocal-implemented-under-the-hood.

If you are eager to know even more details, take a look on ThreadLocal source code: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/ThreadLocal.java + Thread source code: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s