Sunday, June 5, 2016

Java : Usage of ThreadLocal with Example

ThreadLocal is a class in java.lang package. The instance of this class is used as a local variable of the Thread in which it is created. Means that ThreadLocal variable is the personal storage of any Thread. Means that ThreadLocal instance stores the values of the local variables of the Threads. Most important point to note here is that the value of the ThreadLocal variable is different for all the Threads. It means when the single Thread will be shared within multiple objects , each time the ThreadLocal variable's value will be differently stored for each Thread as per the user implementation.

Although, it seems that ThreadLocal is taking the place of Synchronization but is not purely true. Partially we can say that Synchronization and ThreadLocal seems to work similar because in Synchronization also the functionality is similar in the sense that one thread can access the safe area at a time and get or set the values freely without any fear. On the other hand ThreadLocal variable plays the same role for each thread having different values for each Thread . Hence, in some situations if we see in our application that the Synchronization costs too much , we can use ThreadLocal variable and perform our task smoothly because the value of the variables would be different for different thread as per hold in the ThreadLocal variable. Let's take an example to explain better this concept:

public class ThreadLocalExampleClass {

    public static class MyRunnable implements Runnable {

        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

        @Override
        public void run() {
            threadLocal.set( (int) (Math.random() * 100) );   
            System.out.println(threadLocal.get());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyRunnable threadInstance = new MyRunnable();

        Thread thread1 = new Thread(threadInstance);
        Thread thread2 = new Thread(threadInstance);

        thread1.start();
        thread2.start();

    }
}

In the example above, we have created a Thread by implementing Runnable interface, and in the run method we are generating a random number and setting it to the theadLocal variable.

Then, we created the thread instance in the main method and started two threads on the same object. Now, when the first thread will enter the run method the random number generated will be set into this threads's threadLocal variable and when the second thread will enter the run method , again the instance of threadLocal will be created and the random value will be set into that. Hence, two threads on the same object will get and set the different values on the ThreadLocal variable. If we do the same without using ThreadLocal and Synchronization then we can have race condition problem when we are sharing some resource between multiple threads simultaneously. Other way out of this situation is Synchronization but it might be too costly sometimes because one thread will enter the shared object at a time.

Hence, we can conclude that using ThreadLocal variables in the Multi-Threading applications is very helpfull in maintaining the different values for differnt Threads without using Synchronization. This is very usefull in the product selling sites because there the same product can be viewed/update/ordered by multiple users at the same time. Hence, maintaining the history of each customer in the ThreadLocal variable will be very usefull. There we can not use Synchronization because if one user is placing the order, then the other will get blocked till the time. But in the case if we use ThreadLocal, we can easily trace the activities of each user separately. 

No comments:

Post a Comment