Threads · Topic 6 of 7
ThreadLocal
Definition​
A ThreadLocal gives every thread its own copy of a value. It is handy for per-thread context such as the current user or a non-thread-safe helper, but values must be removed when you are done, especially in thread pools.
Example code​
Each thread sees only its own value
class Demo {
static final ThreadLocal<String> currentUser = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
currentUser.set("main-user");
Thread other = new Thread(() -> {
System.out.println("other thread sees: " + currentUser.get()); // null: it has no value yet
currentUser.set("other-user");
System.out.println("other thread now sees: " + currentUser.get());
currentUser.remove(); // clean up when done
});
other.start();
other.join();
System.out.println("main still sees: " + currentUser.get()); // unchanged
}
}
// Output:
// other thread sees: null
// other thread now sees: other-user
// main still sees: main-user
Finished this page? Track your progress (saved only in your browser).