Creating and Using ThreadLocal Variables
What you'll learn: How to declare ThreadLocal instances and use get() and set() to store values that are isolated per thread.
The Core Idea
A ThreadLocal variable acts like a box that gives each thread its own independent storage compartment. When you call get() or set(), you're only accessing your thread's private copy—other threads see their own separate values, even though you're all using the same ThreadLocal instance.
Think of it like hotel room safes: all rooms have a safe in the same location, but each guest can only access their own room's safe with their key. Similarly, each thread has its own "safe" for the ThreadLocal variable.
Declaring a ThreadLocal
You create a ThreadLocal as a static field, parameterized with the type you want to store:
private static ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<>();
Using set() to Store Values
Each thread stores its own value using set():
threadLocalCounter.set(42); // This thread's value is now 42
Using get() to Retrieve Values
Each thread retrieves only its own value using get():
Integer value = threadLocalCounter.get(); // Returns this thread's value
If get() is called before any set(), it returns null (for reference types).
Complete Example
private static ThreadLocal<Integer> counter = new ThreadLocal<>();
Runnable task = () -> {
counter.set(0);
for (int i = 0; i < 5; i++) {
counter.set(counter.get() + 1);
}
System.out.println(Thread.currentThread().getName() + ": " + counter.get());
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
// Each thread prints "5" independently
Key Takeaway: Declare ThreadLocal<T> instances to create per-thread storage; use set(value) to store and get() to retrieve thread-specific values without any explicit synchronization needed.