Java ThreadLocal
ThreadLocal is a class in Java which enables to keep the different copies for each thread. In more general terms lets say thread t1 modified ThreadLocal class variable String from one value to another value this change will not be visible to the other threads although they read the same variable after the change.
This is another way of achieving the thread safety in java.
ThreadLocal Example
public class ThreadLocalExample extends Thread { public ThreadLocal<String> threadLocal; public ThreadLocalExample(ThreadLocal<String> threadLocal) { this.threadLocal=threadLocal; } public static void main(String[] args) { ThreadLocal<String> threadLocal= new ThreadLocal<String>(); new ThreadLocalExample(threadLocal).start(); new ThreadLocalExample(threadLocal).start(); } public void run() { System.out.println("Initial Value : " + threadLocal.get()+" read by "+Thread.currentThread().getName()); //Value fetching by other thread or threads threadLocal.set("Value Set by : " + Thread.currentThread().getName()); //Value Changing by other thread or threads System.out.println("Later Value : " + threadLocal.get()+" read by "+Thread.currentThread().getName()); //Value fetching by other thread or threads } }output
Initial Value : null read by Thread-0 Later Value : Value Set by : Thread-0 read by Thread-0 Initial Value : null read by Thread-1 Later Value : Value Set by : Thread-1 read by Thread-1
If we see the above output, all the threads are sharing the same ThreadLocal variable although each thread have its own copies.