CKTIS / Java
ThreadLocal — a value associated with a thread
ThreadLocal stores a separate value for each thread. Learn lazy initialization, reading, writing, and removal, and why cleanup matters for tasks running in a thread pool.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
ThreadLocal<T> local = ThreadLocal.withInitial(() -> initialValue);
local.set(newValue);
T value = local.get();
local.remove();java.lang.ThreadLocal<T> associates a value with the current thread, not with a task. Multiple threads can use one ThreadLocal field while retaining separate values.
ThreadLocal.withInitial supplies an initializer. ThreadLocal.get initializes the value on first access unless ThreadLocal.set was called earlier. A plain new ThreadLocal<>() creates an instance. The first get() call on that instance returns null if no value has been set for the current thread. ThreadLocal.set changes only the current thread's value.
ThreadLocal.remove deletes the current thread's entry; the next get() initializes it again unless set(...) intervenes. set(null) does not remove the entry.
In a thread pool, a leftover value can reach the next task and retain data unnecessarily. Remove task context in finally. The example demonstrates independent values and reinitialization; join() ensures that the main thread's final output follows the worker's output.
Examples
public class ThreadLocalDemo {
private static final ThreadLocal<String> CONTEXT =
ThreadLocal.withInitial(() -> "unset");
public static void main(String[] args) throws InterruptedException {
try {
CONTEXT.set("main");
Thread worker = new Thread(() -> {
try {
System.out.println("worker initial: " + CONTEXT.get());
CONTEXT.set("worker");
System.out.println("worker set: " + CONTEXT.get());
} finally {
CONTEXT.remove();
}
try {
System.out.println("worker reset: " + CONTEXT.get());
} finally {
CONTEXT.remove();
}
});
worker.start();
worker.join();
System.out.println("main: " + CONTEXT.get());
} finally {
CONTEXT.remove();
}
}
}Result
worker initial: unset worker set: worker worker reset: unset main: main
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.