Sub topic 10
ThreadLocal and Request-Scoped State
This chapter assumes you know Java 21 basics, how ThreadLocal works, and how a Spring MVC request flows through filters and controllers. It covers what changes for per-request state when each request runs on a virtual thread, and what to review before you roll it out.
ThreadLocal still works on virtual threads
A virtual thread is a real java.lang.Thread. Each one has its own ThreadLocal values, and InheritableThreadLocal is also supported. Code that sets a value at the start of a request and reads it later on the same thread keeps working.
Many Spring features depend on this. SecurityContextHolder, RequestContextHolder, transaction synchronization and MDC logging context all store state in thread-locals by default. With spring.threads.virtual.enabled=true, they behave as before, because Tomcat or Jetty still handles one request on one thread from start to finish.
What changes: the number of threads
With a platform thread pool of 200 threads, at most 200 sets of thread-local values exist at once, and the pool reuses them. With virtual threads there is one thread per request, and nothing is reused. Ten thousand concurrent requests means ten thousand threads, each with its own thread-local map.
This causes two problems.
- Memory. Anything you store in a
ThreadLocalexists once per thread. A cachedSimpleDateFormat, a byte buffer or a parser stored per thread was a cheap optimization with 200 pooled threads. With thousands of virtual threads it becomes a large allocation, and the cache never gets reused. - Stale state. Pool-based code sometimes relied on a thread being reused, and on cleanup in a
finallyblock to reset it. Virtual threads end when the task ends, so leftover values are discarded. Code that depends on a value surviving between requests will break.
The first problem is the more common one. Search your code and your libraries for ThreadLocal.withInitial and for thread-local caches.
Reviewing your code
import java.text.SimpleDateFormat;
class LegacyFormatter {
// Allocates one formatter per thread. Fine for 200 pooled threads,
// wasteful for one virtual thread per request.
private static final ThreadLocal<SimpleDateFormat> FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
String format(java.util.Date date) {
return FORMAT.get().format(date);
}
}Replace per-thread caches with an immutable, thread-safe object:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Formatter {
private static final DateTimeFormatter FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
String format(LocalDate date) {
return FORMAT.format(date);
}
}DateTimeFormatter is immutable, so all threads can share one instance. When the cached object is expensive and cannot be shared, use a bounded pool instead of one instance per thread.
Keep a ThreadLocal when it holds small, request-scoped context such as a user id or a trace id. Always remove it when the request ends:
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
class TenantFilter extends OncePerRequestFilter {
static final ThreadLocal<String> TENANT = new ThreadLocal<>();
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
TENANT.set(request.getHeader("X-Tenant"));
try {
chain.doFilter(request, response);
} finally {
TENANT.remove();
}
}
}Child threads do not share the value
A thread-local value is visible only to the thread that set it. If a request handler submits work to another executor, including Executors.newVirtualThreadPerTaskExecutor() from the fan-out chapter, the subtask runs on a new thread and sees null. Pass the value as an argument or capture it in a local variable before you submit the task:
String tenant = TenantFilter.TENANT.get();
Future<String> orders = executor.submit(() -> fetchOrders(tenant));InheritableThreadLocal copies values to child threads, but it copies them for every thread you create. With many short-lived virtual threads, that cost adds up. Prefer explicit arguments.
Scoped values
Java 21 includes ScopedValue as a preview API. It is designed for immutable per-request context shared with child tasks, and it avoids the per-thread memory cost. Because it is a preview feature, it needs --enable-preview. Treat it as something to watch, not as the basis of a production rollout.
Checklist for this chapter
- Search for
ThreadLocalin your code and dependencies. - Replace per-thread caches of expensive objects with shared immutable objects or bounded pools.
- Make sure every
sethas a matchingremovein afinallyblock. - Pass context explicitly to subtasks.
Exercise
A service stores a 64 KB byte buffer in a ThreadLocal to avoid allocating one per call. It ran well on a 200-thread Tomcat pool. After enabling virtual threads, heap use rises sharply under load. Why, and what would you change?
Show answer
With a pool, at most 200 buffers exist and each is reused. With virtual threads, each request runs on a new thread, so each one allocates its own 64 KB buffer that is never reused, and thousands of concurrent requests hold thousands of buffers. Remove the thread-local cache. Allocate the buffer per call, or use a bounded pool of buffers whose size you control.
Exercise
A request handler reads TENANT.get() inside a task submitted to Executors.newVirtualThreadPerTaskExecutor() and gets null. Why, and how do you fix it?
Show answer
Thread-local values belong to the thread that set them, and the subtask runs on a different virtual thread. Read the value in the handler and pass it to the task, for example String tenant = TENANT.get(); followed by executor.submit(() -> fetchOrders(tenant)).