Monday, February 27, 2017

ThreadLocal in Java

ThreadLocal

ThreadLocal is a Java Class which allows to create a local variable for each thread which can be accessible by itself only. That means the value created or assigned by one thread is not visible to other threads.
Let's look at this using an example

Example:

Creating a thread with Class name ThreadExample. The class has a static ThreadLocal variable, which will be set inside the run() method and accessed couple of times. Check below.
package com.test;

public class ThreadExample implements Runnable
{
    private static ThreadLocal<String> t = new ThreadLocal<String>();

    private String i;

    ThreadExample(String i)
    {
        this.i = i;
    }

    public void run()
    {
        t.set(i + " " + Math.random());
        try
        {
            System.out.println(t.get());
            Thread.sleep(10000);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println(t.get());
    }
}

From the main(), two threads created of type ThreadExample and called. See below
package com.test;

public class Application
{
    public static void main(String... strings) throws Exception
    {
        ThreadExample thread = new ThreadExample("ThreadLocal");

        Thread t1 = new Thread(thread); // Creating first thread
        Thread t2 = new Thread(thread); // Creating second thread

        t1.start(); // Starting
        t2.start(); // Starting

        t1.join(); //Waiting for the thread to complete
        t2.join(); //Waiting for the thread to complete

    }
}

Output

Output of the above example is
ThreadLocal 0.7293783856054876
ThreadLocal 0.42852459712457325
ThreadLocal 0.7293783856054876
ThreadLocal 0.42852459712457325

Points to be noted

  • ThreadLocal class is a generic type. You can set any type of Object value in it. In the above example, its String.
  • You can set the value using .set() method and read it using .get() method.
  • Each thread has it's own value inside the variable in ThreadExample. (You can find that in the output above)
  • Even though the variable is static, is not changed by two threads because it's a type of ThreadLocal. Each thread had it's own value in t. It works in the same way, if it's not static also. Just to show it's importance, i made it static.
  • If the variable is not ThreadLocal, both threads might have updated and accessed same value.

InheritableThreadLocal

InheritableThreadLocal extends ThreadLocal, which works in the same way as ThreadLocal except that the value inside it can be accessible by the thread's child as well. 

Thanks for reading. Happy Learning!!!