What is ThreadLocal variable in Java?

ThreadLocal variable

ThreadLocal class in Java provides you to create variables that can only be accessible and written by the same thread. A single instance of ThreadLocal variable can hold different values of threads separately. ThreadLocal variables are private to each thread, it means these variables can only be read and written by the same thread. If two threads are executing inside a process then these two threads can’t see each other’s thread-local variables.
Apart from immutability, ThreadLocal is another way to achieve thread-safety in java.

Methods of ThreadLocal class:

1. get() : Returns the value in the current thread’s copy of this thread-local variable.
2. initialValue() : Returns the current thread’s “initial value” for this thread-local variable.
3. remove() : Removes the current thread’s value for this thread-local variable.
4. set(T value) : Sets the current thread’s copy of this thread-local variable to the specified value.

Creation of ThreadLocal variable

Let see how we can create thread-local variables.

ThreadLocal class provides thread-local variables.

private ThreadLocal threadLocal = new ThreadLocal();

This will instantiate a new ThreadLocal object and needs to be done once for each thread.
When two or more threads executes the same code which accesses a ThreadLocal object then each thread will see only its own ThreadLocal instance.

Uses of ThreadLocal variable

  • ThreadLocal provides wonderful way to implement per thread singleton classes.
  • Wrap any non Thread Safe object in ThreadLocal to make it Thread-safe.
  • A common use of ThreadLocal is seen in DAO pattern where DAO class can be a singleton but database connection  can be used separately for each thread.

Sample Code:

public class MyThreadLocalExample {

    public static void main(String[] args){
        MyThread myThread = new MyThread();

        Thread t1 = new Thread(myThread, "My Thread-A");
        Thread t2 = new Thread(myThread, "My Thread-B");

class MyThread implements Runnable {

    private ThreadLocal myThreadLocal = new ThreadLocal();

    public void run() {

        try {
        } catch (Exception e) {
        System.out.println(Thread.currentThread().getName() + " : " + myThreadLocal.get());


Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com