ThreadLocal
in Java is a special class that provides thread-local variables. Each thread that accesses a ThreadLocal
variable has its own, independently initialized copy of the variable. This is extremely useful when you want to avoid sharing data between threads, such as in cases of per-thread counters, user sessions, or database connections.
Here’s a detailed breakdown:
1. Key Characteristics
- Each thread sees its own version of the variable.
- Variables stored in
ThreadLocal
are not shared between threads. - Helps avoid synchronization when threads need their own copy of data.
- Often used in frameworks, like Spring, for things like request/session scoped data.
2. Basic Usage
public class ThreadLocalExample {
// Create a ThreadLocal variable
private static ThreadLocal<Integer> threadLocalCount = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
Runnable task = () -> {
int count = threadLocalCount.get(); // get current thread's value
count += 1;
threadLocalCount.set(count); // set updated value
System.out.println(Thread.currentThread().getName() + ": " + threadLocalCount.get());
};
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
t1.start();
t2.start();
}
}
Output (example):
Thread-1: 1
Thread-2: 1
Notice that each thread has its own copy of the variable, even though they are using the same
ThreadLocal
object.
3. Methods in ThreadLocal
T get()
: Returns the value in the current thread.void set(T value)
: Sets the value for the current thread.void remove()
: Removes the current thread’s value (important to avoid memory leaks, especially in thread pools).
4. ThreadLocal with Initial Value
You can initialize a ThreadLocal
using:
ThreadLocal<Integer> threadLocalVar = ThreadLocal.withInitial(() -> 100);
5. Use Cases
- Per-thread counters.
- Database connections per thread.
- User session or request context in web applications.
- Avoiding synchronization for thread-specific data.
⚠️ Important Notes
- Always call
remove()
when done with thread pools to prevent memory leaks, because threads can be reused. ThreadLocal
does not make objects thread-safe; it isolates variables per thread.