Sub topic 17
Thread Confinement and ThreadLocal
So far you have protected shared data with locks, volatile, and atomic classes. There is also a simpler option: don't share the data. If only one thread can ever reach an object, no other thread can interfere with it, and you need no synchronization.
What Thread Confinement Means
Thread confinement means keeping an object inside a single thread so that no other thread can see it. A race condition needs at least two threads touching the same data. With confinement, that never happens.
The most common form is a local variable, a variable declared inside a method. Each thread that calls the method gets its own copy on its own stack, the private memory a thread uses for method calls.
public class Totals {
public static int sumTo(int n) {
int total = 0; // local: each thread has its own total
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
}Two threads can call sumTo at the same moment safely. Each one works on its own total.
ThreadLocal: One Copy Per Thread
Sometimes many methods need the same helper object, and making a new one on every call is wasteful. ThreadLocal is a Java class that holds a separate value for each thread. When a thread calls get(), it receives its own copy and never sees another thread's copy.
This works well for classes that are not thread-safe, meaning they break when two threads use one instance. SimpleDateFormat is a well-known example.
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 = () -> {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + 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();
}
}withInitial takes a lambda that creates the first value. The first time a thread calls FORMAT.get(), Java runs the lambda for that thread. Later calls from the same thread return the same object.
When to Use Each Approach
| Approach | Best for | Needs locks? |
|---|---|---|
| Local variables | Temporary data inside one method | No |
| ThreadLocal | A reusable helper object per thread | No |
| Shared object with locks | Data many threads must update together | Yes |
Exercise
Two threads call a method that creates a new ArrayList in a local variable, adds items, and returns its size. Does the list need synchronization? Why or why not?
Show answer
No. The list is stored in a local variable, so each thread creates and uses its own list. It stays confined to one thread unless a reference to it escapes into shared state.
Exercise
Why does DateFormatter use ThreadLocal instead of one shared static SimpleDateFormat?
Show answer
SimpleDateFormat is not thread-safe, so sharing one instance between threads can produce wrong results. ThreadLocal gives each thread its own instance, so no instance is ever shared and no lock is needed.