Sub topic 17
Thread Confinement and ThreadLocal
The earlier chapters fixed race conditions by guarding shared data with locks, volatile, or atomic classes. This chapter avoids the problem differently. If only one thread can ever reach a piece of data, no other thread can race with it, so the data needs no lock.
This idea is called thread confinement. Thread confinement means keeping data inside one thread so that no other thread can read or change it. Confined data is not shared, so it cannot cause a race condition.
Why Confinement Works
A race condition needs three things:
- Data that more than one thread can reach.
- Data that can change (it is mutable).
- At least one thread that writes to it.
Immutability, covered in an earlier chapter, removes the second item. Confinement removes the first. When only one thread can reach the data, the other two items stop mattering.
This makes confinement cheap. A thread never waits for a lock, and no other thread is slowed down. The code also reads like ordinary single-threaded code.
Stack Confinement: Local Variables
The simplest kind of confinement comes free with Java. A local variable is a variable declared inside a method. Each time a method runs, the thread running it gets its own fresh copy of every local variable. These copies live on the thread's stack, which is a private area of memory that each thread owns.
Two threads can call the same method at the same moment and never touch each other's local variables.
import java.util.ArrayList;
import java.util.List;
public class StackConfinement {
static List<Integer> squares(int limit) {
List<Integer> result = new ArrayList<>(); // local: one list per call
for (int i = 1; i <= limit; i++) {
result.add(i * i);
}
return result;
}
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
List<Integer> mine = squares(5);
System.out.println(Thread.currentThread().getName() + " " + mine);
};
Thread t1 = new Thread(task, "worker-1");
Thread t2 = new Thread(task, "worker-2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}ArrayList is not thread-safe. This code is still safe, because each call creates its own list and the list never leaves the thread that made it. Each thread prints [1, 4, 9, 16, 25].
When Local Variables Are Not Enough
Sometimes one object is expensive to create, and you want to reuse it instead of creating a new one on every call. The class still might not be safe to share.
SimpleDateFormat is the classic case. It formats dates into text, but it stores working data in its own fields while it formats. If two threads use the same instance at once, they overwrite each other's working data and can produce wrong dates or throw exceptions.
You have three options:
| Option | Safe? | Cost |
|---|---|---|
| Share one instance with no lock | No | Wrong output or exceptions |
| Share one instance and lock every call | Yes | Threads wait for each other |
| Create a new instance on every call | Yes | Many short-lived objects |
| Give each thread its own instance | Yes | One object per thread |
The last option is what ThreadLocal provides.
ThreadLocal: One Value Per Thread
ThreadLocal<T> is a class in java.lang. A ThreadLocal object looks like one variable, but it holds a separate value for each thread that uses it. When a thread calls get(), it receives its own value. It never sees another thread's value.
Its main methods are:
get()returns the current thread's value.set(value)changes the current thread's value only.remove()deletes the current thread's value.ThreadLocal.withInitial(supplier)creates aThreadLocalthat builds a starting value the first time each thread callsget().
Here is the date formatter made safe with ThreadLocal:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
private static final ThreadLocal<SimpleDateFormat> FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
public static String format(Date date) {
return FORMAT.get().format(date);
}
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 3; i++) {
SimpleDateFormat mine = FORMAT.get();
System.out.println(Thread.currentThread().getName()
+ " uses formatter " + System.identityHashCode(mine)
+ " -> " + format(new Date()));
}
};
Thread t1 = new Thread(task, "worker-1");
Thread t2 = new Thread(task, "worker-2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}System.identityHashCode prints a number that tells objects apart. When you run this, you will see that worker-1 uses the same formatter number all three times, and worker-2 uses a different number. Each thread created its formatter once and reused it. The two threads never shared one.
The FORMAT field itself is shared, because it is static. That is fine. The field is final and never changes. Only the values it hands out are per thread, and each of those stays confined.
ThreadLocal for Per-Request Context
A second common use is to carry information about the current task, such as which user made a request, without passing it into every method.
Servers usually run tasks on a thread pool. A thread pool is a fixed group of threads that are reused to run many tasks, one after another. Reuse is the source of a serious gotcha. A thread keeps its ThreadLocal value after a task finishes. If you forget to clear the value, the next task on that thread can read the previous task's data.
The fix is to call remove() in a finally block:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class RequestContext {
private static final ThreadLocal<String> USER = new ThreadLocal<>();
static void handle(String user) {
USER.set(user);
try {
log("start");
log("done");
} finally {
USER.remove(); // clear before the pool reuses this thread
}
}
static void log(String message) {
System.out.println(Thread.currentThread().getName()
+ " [" + USER.get() + "] " + message);
}
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
for (String user : new String[] {"alice", "bob", "carol", "dave"}) {
pool.submit(() -> handle(user));
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}Two threads handle four users. The log method never takes a user parameter, yet each line shows the right user, because USER.get() returns the value for the thread that is running.
Common Mistakes
- Leaking the confined object. Storing a
ThreadLocalvalue in a shared field or returning it to code that hands it to another thread ends the confinement. - Forgetting
remove()in pools. Stale values carry over to unrelated tasks. - Expecting child threads to see the value. A new thread starts with no value in a plain
ThreadLocal. It does not copy the value from the thread that started it. - Using ThreadLocal to dodge design. Too many
ThreadLocalfields hide where data comes from. Passing a parameter is often clearer.
Choosing an Approach
Use confinement when each thread can work with its own copy of the data. Prefer plain local variables first, since they need no extra code. Reach for ThreadLocal when an object is costly to create and is not thread-safe, or when per-task context must reach code deep in the call chain. If threads truly need to see one another's changes, confinement cannot help, and you need the locks, atomic classes, or concurrent collections from earlier chapters.
Exercise
A method creates a new HashMap in a local variable, fills it, and then stores it in a static field named latest so other threads can read it. Is the map still thread-confined? Explain.
Show answer
No. The map was confined while only the local variable referred to it. Storing it in a static field lets it escape, so other threads can reach it. It is now shared mutable state and needs synchronization, a concurrent collection, or an immutable copy.
Exercise
A web server uses a pool of 10 threads. Each request calls USER.set(name) on a ThreadLocal but never calls remove(). What can go wrong?
Show answer
Pool threads are reused. If a later request on the same thread reads USER before it calls set, it gets the previous request's user name. That can show one user's data to another. The old values also stay in memory as long as the thread lives. Call remove() in a finally block after each request.
Exercise
Why is it safe for many threads to use the same static final ThreadLocal<SimpleDateFormat> field, even though SimpleDateFormat is not thread-safe?
Show answer
The ThreadLocal object is shared, but it gives each thread its own SimpleDateFormat instance. No formatter is ever used by two threads, so the formatter's internal fields are never accessed concurrently.