Saturday, 28 February 2015

ThreadLocal class


ThreadLocal class is used to create variable that are local to thread. In technical terms, ThreadLocal is used to create thread safe variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

Every thread has its own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change its value local to Thread.

public class Transaction implements Runnable{
    private static final ThreadLocal<Integer> transId = new ThreadLocal<Integer> ();
    private int id;

    public void run() {
        transId.set(id);
        System.out.println(Thread.currentThread().getName() + " " + transId.get());
        try{
            Thread.sleep(5000);
        }catch(InterruptedException e){

        }
        System.out.println(Thread.currentThread().getName() + " " + transId.get());
        transId.remove();
    }

    Transaction(int id){
        this.id = id;
    }

}


public class ThreadLocalTest {
    public static void main(String args[]){
        Transaction trans1 = new Transaction(1);
        Transaction trans2 = new Transaction(2);
        Transaction trans3 = new Transaction(3);
        Transaction trans4 = new Transaction(4);
        Transaction trans5 = new Transaction(5);

        Thread t1 = new Thread(trans1);
        Thread t2 = new Thread(trans2);
        Thread t3 = new Thread(trans3);
        Thread t4 = new Thread(trans4);
        Thread t5 = new Thread(trans5);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
}

Sample Output
Thread-2 3
Thread-1 2
Thread-0 1
Thread-4 5
Thread-3 4
Thread-2 3
Thread-1 2
Thread-3 4
Thread-0 1
Thread-4 5


private static final ThreadLocal<Integer> transId = new ThreadLocal<Integer> ();
Above statement instantiate ThreadLocal instance. All threads will see the same ThreadLocal instance, but the values set on the ThreadLocal via its set() method will only be visible to the thread that set the value. Even if two different threads set different values on the same ThreadLocal object, they cannot see each other's values.

Note:
Always remove the thread local variable after it’s usage. ThreadLocal's remove() method can be used to remove variable. If you are using ThreadLocal in web application and failed to remove after it’s usage causes memory leak in your application.



No comments:

Post a Comment