Friday, October 5, 2012

Usage of ThreadLocal in Java

The ThreadLocal class is an important yet often neglected class in the java default library. Many developers don't understand the usage of this class so this is my attempt to explain it.

The definition of this class in official javadoc is

"This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable"

So according to the definition if an Instance of ThreadLocal variable is accessed by different threads each thread will get a copy of the variable which is not shared or visible by other threads. Simply put this class enables Thread confinement of variables. The usual approach developers use to have independent variables in different threads is they initialize and assign each thread an object instance which implements Runnable or extends Thread where the required variable is an instance variable in that object. 

But ThreadLocal is ideal where you want to initialize one object and assign them to different threads yet have independent variables. The following example shows the class at work.

public class ThreadLocalTest implements Runnable {
    private static ThreadLocal<Integer> no = new ThreadLocal<Integer>() {
        public Integer initialValue() {
            return 0;
        }
    };
    
    public static void main(String[] args) {
        Thread t1 = null;
        // Single Object
        ThreadLocalTest test = new ThreadLocalTest();
        for(int i=0;i<10;i++) {
            // test object is used in 10 Threads
            t1 = new Thread(test);        
            t1.start();
        }        
    }
    
    public void run() {
        System.out.printf("Before %s : %d\n", Thread.currentThread().getName(), no.get());
        no.set(no.get() + 1);
        System.out.printf("After %s : %d\n", Thread.currentThread().getName(), no.get());
    }
}

Only one object is created and used in 10 different threads yet each thread has its own initialized variable 'no'.

No comments: