threadlocal in java

ThreadLocal in Java

ThreadLocal allows us to create variable that can only be read and written by the same thread.
ThreadLocal variables can be read and written within one thread anywhere,
which means it’s global in one thread, while no other thread can have access to the the thread’s ThreadLocal variable.

Create a ThreadLocal

We can create a generic ThreadLocal or not generic.

ThreadLocal<String> strThreadLocal = new ThreadLocal<>();

ThreadLocal threadLocal = new ThreadLocal();

Set value

strThreadLocal.set("Hello world");

Get vale

String str = strThreadLocal.get();

Full example

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

        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        thread1.start();
        thread2.start();
    }
}

class MyThread implements Runnable {
    private ThreadLocal<Double> threadLocal = new ThreadLocal<>();

    @Override
    public void run() {
        threadLocal.set(Math.random() * 1000);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());
    }
}

Output:
Thread-1: 849.8070778476954
Thread-0: 374.3590156835318

The output of the two threads are different, because they have their own thread local variables.