Sub topic 10
Thread Locals When Threads Are Plentiful
A thread local is a variable that holds a separate value for each thread. When thread A sets it, thread B does not see that value. Java provides this through the ThreadLocal class. Virtual threads support thread locals the same way platform threads do. The way you use them sometimes has to change, though, because you will now have far more threads than before.
Why thread locals were popular
With a thread pool, a small number of threads (often 10 to 200) live for a long time. Each one runs thousands of tasks. Programmers took advantage of this. They stored an expensive object in a thread local, such as a buffer or a formatter, so that each pool thread created it once and reused it for every task it ran.
That trick depends on threads being few and long-lived. With virtual threads, each task usually gets its own new thread. The thread ends when the task ends. Nothing gets reused, so the cache never saves any work.
Seeing the cost
This program counts how many buffers the thread local creates.
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalCost {
static final AtomicInteger created = new AtomicInteger();
static final ThreadLocal<StringBuilder> BUFFER =
ThreadLocal.withInitial(() -> {
created.incrementAndGet();
return new StringBuilder(1024);
});
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
int id = i;
executor.submit(() -> {
StringBuilder sb = BUFFER.get();
sb.setLength(0);
sb.append("task ").append(id);
return sb.toString();
});
}
}
System.out.println("Buffers created: " + created.get());
}
}It prints Buffers created: 10000. If you replace the executor with Executors.newFixedThreadPool(8), it prints 8 or fewer. With virtual threads, the "cache" uses more memory and saves no work. With a million tasks, it creates a million buffers.
Better habits
Most of the time you can drop the thread local completely.
| Old habit | Better choice with virtual threads |
|---|---|
| Cache a `SimpleDateFormat` per thread | Share one `DateTimeFormatter`. It is immutable and thread-safe. |
| Cache a big buffer per thread | Create a small object inside the task, or share a thread-safe one |
| Pass request data through a thread local | Pass it as a method parameter when you can |
| Forget to clean up | Call `remove()` when you are done |
Here is the formatter fix. A single shared object works for every thread:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SharedFormatter {
private static final DateTimeFormatter FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual().start(() ->
System.out.println(FORMAT.format(LocalDate.of(2024, 3, 15))));
t.join();
}
}A later chapter introduces scoped values, a newer API built for sharing data safely with many threads.
Exercises
Exercise
A program runs 50,000 tasks with Executors.newVirtualThreadPerTaskExecutor(). Each task calls get() on a ThreadLocal whose withInitial() creates a 1 KB object. About how many of those objects are created, and why?
Show answer
About 50,000. Each task runs on its own new virtual thread, and every new thread gets its own fresh value, so nothing is reused.
Exercise
Your old code keeps a SimpleDateFormat in a ThreadLocal because SimpleDateFormat is not thread-safe. What should you use when you move to virtual threads?
Show answer
One shared static DateTimeFormatter. It is immutable and thread-safe, so every virtual thread can use the same instance without a thread local.