Monday, 23 November 2015

Secrets of java.lang.ThreadLocal - Part I

java.lang.ThreadLocal is given by Java API to achieve the thread-safety in multi-threaded environment. Unlike of synchronization or locking this eliminates the sharing concept rather maintains an individual copy of object for each thread. So no need of locking or synchronization which results more scalability and performance.

Here id and threadLocal both are shared resources but ThreadLocal maintains individual copy for each thread.

Now the Secret of ThreadLocal is
- Each Thread object contains an instance member variable as ThreadLocal.ThreadLocalMap threadLocals;
- Where as ThreadLocal.ThreadLocalMap contains array of entries of java.lang.ref.Reference type as private Entry[] table;
And this Entry is a simple <key, value> pair like Map.Entry which contains ThreadLocal<?> as key and Object as value
- ThreadLoacl class has 2 important methods 
public void set(T value) : while setting the value, it first gets the ThreadLocalMap of the current thread. Then adds an entry with <this ThreadLocal object, passed Value>
* public T get() : while getting the value, first gets the ThreadLocalMap of the current thread. Then get the value for the Entry by passing key as this current ThreadLocal object. If not found any value then sets and returns the initial value provided by the programmer. 
ThreadLocal class having a callback method to provide the initial value as protected T initialValue(); ]

To provide initial value we can override callback method as below :
ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
    @Override    protected Integer initialValue() {
        return 100;

No comments:

Post a Comment