ThreadLocal Variable in Java
In Java, ThreadLocal is a class that provides thread-local variables. A thread-local variable is a variable that is specific to each thread, meaning that each thread accessing the variable has its own independent copy. This allows threads to have their own instance of a variable without the need for synchronization, which can improve performance and simplify concurrency management in certain scenarios.
Table of Contents
Here’s how ThreadLocal works:
- Each thread that accesses a ThreadLocal variable has its own separate copy of that variable.
- When a thread accesses or sets the value of a ThreadLocal , it’s manipulating its own copy of the variable, which is not visible to other threads.
- ThreadLocal instances are typically declared as static fields in classes, allowing them to be accessed by multiple threads within the same class or across different classes.
ThreadLocal is often used in scenarios where each thread needs its own instance of a variable, such as maintaining user sessions in web applications, database connections, or thread-specific logging.
Let’s illustrate the usage of ThreadLocal in Java with an example:
java
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocalVariable = new ThreadLocal<>();
public static void main(String[] args) {
// Setting values for thread-local variable in multiple threads
Thread thread1 = new Thread(() -> {
threadLocalVariable.set(10);
System.out.println("Thread 1 - ThreadLocal variable value: " + threadLocalVariable.get());
});
Thread thread2 = new Thread(() -> {
threadLocalVariable.set(20);
System.out.println("Thread 2 - ThreadLocal variable value: " + threadLocalVariable.get());
});
thread1.start();
thread2.start();
}
}
In this example, we have a ThreadLocal variable threadLocalVariable, which stores integer values. Two threads (thread1 and thread2) are created and started. Each thread sets a different value for the threadLocalVariable using the set() method and retrieves its value using the get() method. Each thread operates independently on its own copy of the ThreadLocal variable, so changes made by one thread are not visible to the other thread. This demonstrates the thread isolation provided by variables.