Sub topic 10
ThreadLocal and Request-Scoped State
This chapter assumes you know what a virtual thread is, that you have enabled spring.threads.virtual.enabled=true, and that you are comfortable with ThreadLocal basics. It covers how ThreadLocal behaves on virtual threads, where it still works, where it causes trouble, and what to do about it.
Do virtual threads support ThreadLocal?
Yes. A virtual thread is a Thread, and it has its own ThreadLocal values, just like a platform thread. Code that calls set, get, and remove on a ThreadLocal behaves the same way. This is why most Spring features that depend on thread-bound state keep working after you turn on virtual threads:
SecurityContextHolderuses a thread-local strategy by default.RequestContextHolderexposes the current request to request-scoped beans.- Transaction synchronization stores the current connection and transaction state per thread.
- MDC (Mapped Diagnostic Context) in SLF4J and Logback keeps log fields such as a trace ID per thread.
In the thread-per-request model, one thread handles one request from start to finish. That is the property these features rely on. Virtual threads preserve it, because the web server still gives each request its own thread. The thread is just cheaper.
What changes: lifetime and count
The difference is not correctness. It is how many threads exist and how long they live.
With a platform thread pool, a few hundred threads are reused for millions of requests. A thread-local value that you forget to clear stays on the pooled thread and can leak into the next request that uses it. This is a well-known bug, and it is why frameworks clear their state at the end of each request.
With virtual threads, the server creates a new virtual thread for each request. When the request ends, the thread ends, and its thread-local values become garbage. That reduces the leak-between-requests risk. It does not remove it in every case. Two situations still matter:
- Code that runs on a shared platform thread pool, such as a custom
ThreadPoolExecutoror a scheduler, still reuses threads. - A virtual thread that lives a long time, such as one that runs a loop, keeps its values until it ends.
The second consequence is memory. You may now have tens of thousands of live virtual threads. If each one holds a large object in a ThreadLocal, the total memory use is the object size multiplied by the number of threads. A cache that was fine with 200 threads can be a problem with 50,000.
import java.text.SimpleDateFormat;
class DateFormats {
// Pattern that made sense with a small pool of platform threads.
// With virtual threads, every request thread builds its own copy.
private static final ThreadLocal<SimpleDateFormat> FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
static String format(java.util.Date date) {
return FORMAT.get().format(date);
}
}This code works. It is wasteful, because each short-lived virtual thread creates a formatter that it uses once and discards. Pooling expensive objects through ThreadLocal only pays off when threads are long-lived and few. Here, the better fix is to use an immutable, thread-safe type.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class DateFormats {
// DateTimeFormatter is immutable and thread-safe, so one shared instance is enough.
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
static String format(LocalDate date) {
return FORMAT.format(date);
}
}Review checklist for ThreadLocal usage
Search your code and your dependencies for ThreadLocal. For each use, ask which of these categories it belongs to.
| Use | Example | Risk with virtual threads | Action |
|---|---|---|---|
| Request context | MDC, security context, request attributes | Low. One value per request thread. | Keep. Make sure it is set at the start and cleared at the end. |
| Object cache | `SimpleDateFormat`, `MessageDigest`, large buffers | Memory grows with thread count. Little reuse. | Replace with a shared thread-safe object, or a bounded pool. |
| Hand-off between steps | Value set in a filter and read in a service | Low, if all steps run on the same thread. | Keep. Check for async boundaries. |
| Pool-wide state | Value set on a shared platform thread | Leaks between tasks. | Always call `remove()` in a `finally` block. |
Context does not follow work to other threads
A ThreadLocal value belongs to one thread. If your code hands work to another thread, the new thread does not see the value. This is true for platform and virtual threads alike, and it matters more once you start using the fan-out pattern from the previous chapters.
import java.util.concurrent.Executors;
class ContextDemo {
private static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) throws Exception {
USER.set("alice");
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
String seen = executor.submit(() -> String.valueOf(USER.get())).get();
System.out.println("child saw: " + seen);
}
System.out.println("parent sees: " + USER.get());
}
}This prints child saw: null and parent sees: alice. The task runs on a new virtual thread, which starts with an empty ThreadLocal. When you fan out work from a request, this means the security context, the MDC, and the request attributes are all missing in the subtasks.
There are two ways to handle it.
The first is to pass the data explicitly. Read the value in the request thread and give it to the task as an argument or a captured local variable. This is simple, and it shows the dependency in the code.
import java.util.concurrent.Executors;
class ExplicitPassing {
private static final ThreadLocal<String> USER = new ThreadLocal<>();
static String run() throws Exception {
USER.set("alice");
String user = USER.get(); // capture on the request thread
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
return executor.submit(() -> "loaded orders for " + user).get();
}
}
}The second is to copy context automatically. Spring provides TaskDecorator for its task executors, and Spring Security offers wrappers such as DelegatingSecurityContextExecutor that copy the security context into the task. Micrometer's context propagation library does the same for MDC and tracing data. Use these when many call sites need the same context and passing arguments by hand would be repetitive.
InheritableThreadLocal
InheritableThreadLocal copies the parent's value into a child thread when the child is created. It works on virtual threads. But it copies at thread creation, so with one new thread per task, every task makes a copy of every inheritable value. Many threads multiplied by many values adds cost. The copy is also a snapshot: later changes in the parent do not reach the child, and later changes in the child do not reach the parent.
You can opt a thread out of inheriting values. Thread.ofVirtual().allowSetThreadLocals(false) creates a thread that cannot hold thread-local values at all, and inheritInheritableThreadLocals(false) skips the copy. Both are rarely needed in application code. They matter mostly for library authors who want to guarantee low overhead.
Scoped values: a preview alternative
Java 21 includes ScopedValue as a preview API (JEP 446). It is designed for the case virtual threads create: sharing immutable data within a bounded piece of code and its child tasks. A value is bound for the duration of a method call, and it disappears when the call returns. It cannot be changed by callees, and it needs no remove() call.
Because it is a preview feature in Java 21, you must compile and run with --enable-preview, and the API can change in later releases. Spring Boot's own infrastructure does not use it yet. For a production application on Java 21, treat it as something to watch, not something to adopt. Keep ThreadLocal for request context, and fix the specific problems described in this chapter.
Common errors
- Assuming context reaches subtasks. Missing MDC fields or an anonymous security context in fan-out code means the values stayed on the request thread. Pass them explicitly or use a propagating executor.
- Leaving a value on a shared thread. On any reused platform thread, call
remove()in afinallyblock. Do not rely on thread death to clean up. - Caching large objects per thread. Memory use now scales with concurrent requests, not with pool size. Measure heap use under load before and after the change.
- Using ThreadLocal as a pool. If the point is to reuse an expensive object, a shared thread-safe instance or a bounded pool of objects works better with many short-lived threads.
Summary of the working model
Exercise
A service sets MDC.put("traceId", id) in a filter. A controller then submits two tasks to Executors.newVirtualThreadPerTaskExecutor(), and the log lines from those tasks have no traceId. Why does this happen, and what are two ways to fix it?
Show answer
MDC is stored in a thread-local, and each task runs on a new virtual thread that starts with no values, so the trace ID stays on the request thread. Fix it by reading the ID on the request thread and setting it inside the task (and clearing it in a finally block), or by wrapping the executor or task with a context-propagating decorator such as one from Micrometer's context propagation library.
Exercise
Your application caches a 64 KB buffer in a ThreadLocal on each thread. It ran well with 200 Tomcat threads. After enabling virtual threads, you see 20,000 concurrent requests. Roughly how much memory do those buffers use, and what would you change?
Show answer
About 1.3 GB (20,000 × 64 KB, roughly 1,280 MB), since each live virtual thread holds its own buffer. Replace the per-thread buffer with a bounded pool of buffers, borrowed and returned per use, or allocate a buffer only when needed, so memory depends on pool size and not on the number of threads.