Sub topic 10
Thread Locals When Threads Are Plentiful
So far you have created virtual threads, run thousands of them with an executor, and limited access to scarce resources with a semaphore. This chapter covers a Java feature called the thread local. Thread locals keep working with virtual threads, but one common way of using them stops paying off once you have one thread per task. You will learn what still works, what breaks, and what to do instead.
What a Thread Local Is
A thread local is a variable where each thread sees its own separate value. In Java it is the class ThreadLocal<T>. When thread A calls set("alice") and thread B calls set("bob"), thread A reads back "alice" and thread B reads back "bob". The two values never mix.
Programs use thread locals for two main jobs:
- Context: carrying information about the current request, such as the user's name or a request ID, so you don't have to pass it through every method call.
- Caching: keeping one copy of an object that is expensive to create, or not safe to share, for each thread, so the thread can reuse it across many tasks.
Virtual threads support thread locals fully. Each virtual thread has its own set of values, the same way a platform thread does.
Thread Locals for Request Context Still Work
Here is a thread local that holds the current user. Two virtual threads each set their own value, and each one reads back only its own.
public class RequestContext {
private static final ThreadLocal<String> USER = new ThreadLocal<>();
static void handle(String user) {
USER.set(user);
try {
logStep("start");
logStep("finish");
} finally {
USER.remove(); // clean up when the task ends
}
}
static void logStep(String step) {
System.out.println(USER.get() + ": " + step);
}
public static void main(String[] args) throws InterruptedException {
Thread a = Thread.ofVirtual().start(() -> handle("alice"));
Thread b = Thread.ofVirtual().start(() -> handle("bob"));
a.join();
b.join();
}
}The output shows alice: start, alice: finish, bob: start, and bob: finish. The lines from the two threads may interleave, but alice's lines never show bob's name.
Request context is a good fit for virtual threads. Each task gets a fresh virtual thread, so the value lives exactly as long as the task. The finally block with remove() is still good practice. It makes your code safe if someone later runs it on a thread pool, where threads are reused and an old value could leak into the next task.
The Caching Pattern Stops Working
The second job, caching, is where things change. With a thread pool, a small number of threads run a very large number of tasks. If each thread caches one expensive object, that object gets reused hundreds or thousands of times.
With virtual threads you don't pool. Every task gets a brand-new thread. A brand-new thread has an empty thread local, so it creates a brand-new object. The "cache" is used once and then thrown away. You pay the full creation cost on every task, and if many tasks are running at the same moment, you hold many copies in memory at once.
The program below counts how many 64 KB buffers get created when 10,000 tasks run first on a fixed pool of 8 threads, and then on virtual threads.
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheCount {
static final AtomicInteger CREATED = new AtomicInteger();
static final ThreadLocal<byte[]> BUFFER = ThreadLocal.withInitial(() -> {
CREATED.incrementAndGet();
return new byte[64 * 1024];
});
static void work() {
byte[] buffer = BUFFER.get();
buffer[0] = 1; // pretend to use the buffer
}
public static void main(String[] args) {
try (var pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 10_000; i++) {
pool.submit(CacheCount::work);
}
}
System.out.println("Fixed pool of 8: " + CREATED.getAndSet(0) + " buffers");
try (var virtual = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
virtual.submit(CacheCount::work);
}
}
System.out.println("Virtual threads: " + CREATED.get() + " buffers");
}
}ThreadLocal.withInitial takes a supplier, which is a function that makes the first value the first time a thread calls get(). On JDK 21 the output is:
Fixed pool of 8: 8 buffers
Virtual threads: 10000 buffersThe pool made 8 buffers and reused them. The virtual threads made 10,000 buffers, about 640 MB of allocations in total, and each buffer was used once.
What to Use Instead of a Thread-Local Cache
Look at why the object was cached in the first place. The fix depends on the reason.
| Reason for the cache | Better choice with virtual threads |
|---|---|
| The old class was not safe to share (for example `SimpleDateFormat`) | Switch to a newer class that is safe to share (for example `DateTimeFormatter`) and keep one copy in a `static final` field |
| The object is cheap to create | Create it inside the task as a normal local variable |
| The object is expensive and must not be shared at the same time (for example a large buffer or a connection) | Keep a small shared pool of the objects, guarded by a `Semaphore` or a blocking queue |
| You use it to pass request context | Keep the thread local, or move to scoped values later |
A class that is thread-safe can be used by many threads at the same time without breaking. SimpleDateFormat is not thread-safe, and that is why older code often put one in a thread local. DateTimeFormatter from java.time is immutable. Immutable means it never changes after it is created, so it is always safe to share. One copy serves every virtual thread:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
public class SharedFormatter {
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5; i++) {
int day = i + 1;
executor.submit(() -> System.out.println(FORMAT.format(LocalDate.of(2026, 11, day))));
}
}
}
}This prints five dates from 2026-11-01 to 2026-11-05, in some order. There is one formatter in memory, no matter how many virtual threads run.
Memory: Small Values, Many Threads
Even context values add up. Say each request stores a 1 KB object in a thread local and one million virtual threads are alive at once. That is about 1 GB of memory held just by thread locals. With a pool of 200 platform threads, the same value took only about 200 KB.
Keep the values you store in thread locals small. Store an ID or a short string, not a whole data structure. Clear them with remove() when you are done, so the garbage collector can reclaim them as early as possible.
Inheritable Thread Locals Get Copied
An InheritableThreadLocal is a special thread local whose value gets copied from a parent thread to each child thread it creates. The parent thread is the one that calls start(), and the child thread is the new one. Virtual threads inherit these values by default, just like platform threads.
Copying is cheap for one thread. If a task starts thousands of virtual threads, though, every one of them gets a copy of every inheritable value. If the children don't need those values, you can turn inheritance off with the builder method inheritInheritableThreadLocals(false):
public class InheritDemo {
static final InheritableThreadLocal<String> TENANT = new InheritableThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
TENANT.set("acme");
Thread copies = Thread.ofVirtual()
.start(() -> System.out.println("default: " + TENANT.get()));
copies.join();
Thread noCopy = Thread.ofVirtual()
.inheritInheritableThreadLocals(false)
.start(() -> System.out.println("no inherit: " + TENANT.get()));
noCopy.join();
}
}The output is:
default: acme
no inherit: nullFinding Thread-Local Use in Your Program
Thread locals are often hidden inside libraries, such as logging tools, older date code, or database drivers. To find out where virtual threads set thread-local values, start the JVM with this system property:
java -Djdk.traceVirtualThreadLocals=true CacheCount.javaWhen a virtual thread sets a thread-local value, the JVM prints a stack trace that shows which code did it. A stack trace is the list of method calls that led to that point. Use it to spot libraries that quietly cache objects per thread.
Summary
- Thread locals work with virtual threads, and each virtual thread has its own values.
- Using them for request context is fine. Keep values small and always call
remove()infinally. - Using them as a per-thread cache does not work, because virtual threads are never reused. Share a thread-safe object, create the object locally, or keep a small pool guarded by a semaphore.
- Inheritable thread locals are copied into every child thread. Turn this off with
inheritInheritableThreadLocals(false)when the children don't need the values. -Djdk.traceVirtualThreadLocals=trueshows where virtual threads set thread locals.
Exercise
A program caches a SimpleDateFormat in a ThreadLocal so each thread has its own copy. After moving to Executors.newVirtualThreadPerTaskExecutor(), it handles 50,000 requests. About how many SimpleDateFormat objects get created, and what is a better design?
Show answer
About 50,000, one per request, because each request runs on a new virtual thread with an empty thread local. A better design is to replace SimpleDateFormat with an immutable DateTimeFormatter stored once in a static final field and shared by all threads.
Exercise
In the CacheCount program, why does the fixed pool create exactly 8 buffers while the virtual-thread executor creates 10,000?
Show answer
The fixed pool has 8 threads that are reused for all 10,000 tasks, so each thread creates its buffer once and reuses it. The virtual-thread executor starts a new thread for every task, and each new thread's first call to BUFFER.get() runs the initializer again.
Exercise
A parent virtual thread sets an InheritableThreadLocal and then starts 10,000 child virtual threads that never read it. What builder setting avoids copying the value into each child?
Show answer
Create the children with Thread.ofVirtual().inheritInheritableThreadLocals(false). The children then start with no inherited values, so TENANT.get() would return null in them.