Spring and ThreadLocals: Request Context Across Threads
Most Spring applications move some work to other threads. This guide explains how Spring uses ThreadLocals to manage request context, and how to keep that work correct when it runs outside the request thread.
Introduction
Spring MVC's programming model rests on a simple assumption: a request is handled by one thread from start to finish. Transaction management, request-scoped beans and locale resolution all depend on it. Spring keeps the context each one needs in a ThreadLocal, so the code that needs it finds it without anything being passed in.
The assumption holds until part of the work moves to another thread, which applications often do: through @AsyncCompletableFuture
This guide explains how Spring binds context to a thread, what each common way of moving work to another thread carries with it, and how to handle the transaction, the request and the locale correctly in each case.
How Spring binds context to a thread
In a standard Spring MVC application, the servlet container takes a thread from its pool for each request, and that thread runs the filters, the controller, the services and the repositories, then writes the response. This guide covers controller methods that return their result directly. Methods that return a CallableDeferredResult
Because one thread handles the whole request, that thread is a convenient place to keep information about it. Java provides the mechanism: a ThreadLocal
Spring uses this for three features that most applications rely on. Each needs some context about the current request, and Spring keeps that context in a ThreadLocal inside a holder class, which application code rarely calls directly:
| What you use | What it needs | Where Spring keeps it |
|---|---|---|
@TransactionalJdbcTemplate | The current transaction and its database connection | TransactionSynchronizationManager |
| Request-scoped and session-scoped beans | The current HTTP request | RequestContextHolder |
| Localized validation messages, date and number formatting | The user's locale and time zone | LocaleContextHolder |
When a transaction begins, the transaction manager stores it in a ThreadLocal on the current thread (Spring calls this binding) and removes it when the transaction commits or rolls back. DispatcherServletRequestContextFilter
This is why a method annotated with @Transactional
Two consequences matter for the rest of this guide. A new thread starts without any of this context. And threads in a pool are reused, so whatever a task leaves on a pooled thread is still there for the next task.
What happens when work moves to another thread
The common ways of moving work to another thread differ in where the work runs, and that decides what context it sees:
| Approach | Where the work runs | Request context available by default |
|---|---|---|
@Async | A pool with 8 core threads, or a new virtual thread per task when virtual threads are enabled | None |
CompletableFuture.supplyAsync(...) | ForkJoinPool.commonPool() | None |
Your own ExecutorService | The executor's threads | None |
parallelStream() | The calling thread and the common pool | Only for the part of the work the calling thread does |
What this means depends on the kind of context.
The request. A request-scoped bean, or a call to RequestContextHolder.currentRequestAttributes()tenantContext
ScopeNotActiveException: Error creating bean with name
'scopedTarget.tenantContext': Scope 'request' is not active for the current
thread; ...
Caused by: IllegalStateException: No thread-bound request found: Are you
referring to request attributes outside of an actual web request, or
processing a request outside of the originally receiving thread? ...
If the @Asyncvoid
The transaction. Code on another thread runs outside the caller's transaction and uses its own database connection. Under the isolation levels databases use by default, it cannot see rows the caller has written until the caller's transaction commits, and because it runs at the same time, it may look for them before that happens. A background task that loads an order its caller has just saved may therefore find nothing.
The locale. LocaleContextHolder.getLocale()
All of this follows from how ThreadLocals work in plain Java, so it can be shown without Spring. The examples below use one ThreadLocal, USERlog
static final ThreadLocal<String> USER = new ThreadLocal<>();
static void log(String what) {
System.out.printf("%-46s user=%s%n",
Thread.currentThread().getName() + ": " + what, USER.get());
}
A task submitted to an executor runs without the value:
ExecutorService pool = Executors.newFixedThreadPool(1);
USER.set("alice");
log("request thread");
pool.submit(() -> log("pool task")).get();
main: request thread user=alice
pool-1-thread-1: pool task user=null
So does CompletableFuture
USER.set("alice");
log("request thread");
CompletableFuture.supplyAsync(() -> { log("supplyAsync"); return 1; }).get();
main: request thread user=alice
ForkJoinPool.commonPool-worker-1: supplyAsync user=null
A parallel stream is less obvious. The calling thread takes part in the work, so the elements it processes see the value, and the elements processed by the common pool do not:
USER.set("alice");
Map<String, Long> seen = IntStream.range(0, 10_000).parallel().boxed()
.collect(Collectors.groupingByConcurrent(
i -> (USER.get() == null ? "user=null " : "user=alice ")
+ Thread.currentThread().getName(),
Collectors.counting()));
new TreeMap<>(seen).forEach((k, v) ->
System.out.println(k + " -> " + v + " elements"));
user=alice main -> 1563 elements
user=null ForkJoinPool.commonPool-worker-1 -> 1250 elements
user=null ForkJoinPool.commonPool-worker-2 -> 1562 elements
user=null ForkJoinPool.commonPool-worker-3 -> 625 elements
user=null ForkJoinPool.commonPool-worker-4 -> 937 elements
user=null ForkJoinPool.commonPool-worker-5 -> 625 elements
user=null ForkJoinPool.commonPool-worker-6 -> 2188 elements
user=null ForkJoinPool.commonPool-worker-7 -> 1250 elements
In this run, 1,563 of 10,000 elements saw the value, and the split changes from run to run. Code inside a parallel stream that reads request context therefore works for some elements and not for others.
Handling context across threads
The right approach depends on the kind of context. Context that holds a resource, such as the transaction and its database connection, should stay on its thread. Context that only describes the request, such as a tenant id or the locale, can be passed to other threads, as long as that is done deliberately.
The transaction: start a new one after the commit
Say an order is saved and a confirmation should be sent in the background. If the code that saves the order calls an @Async
Spring supports this directly. The caller publishes an event, and an asynchronous transactional event listener handles it once the transaction has committed, which is the listener's default phase:
@Service
class OrderService {
private final OrderRepository orders;
private final ApplicationEventPublisher events;
OrderService(OrderRepository orders, ApplicationEventPublisher events) {
this.orders = orders;
this.events = events;
}
@Transactional
public Order place(Order order) {
Order saved = orders.save(order);
events.publishEvent(new OrderPlaced(saved.getId()));
return saved;
}
}
@Component
class ConfirmationSender {
@Async
@TransactionalEventListener
public void onOrderPlaced(OrderPlaced event) {
// runs on another thread, after the order has been committed
}
}
Three details are worth knowing:
needs@Async on a configuration class. Spring Boot does not switch it on by itself.@EnableAsync- If the listener writes to the database, give it its own transaction with
. The caller's transaction has already finished, so there is nothing to join. Spring allows only@Transactional(propagation = Propagation.REQUIRES_NEW) orREQUIRES_NEW here; with any other propagation, the application fails to start.NOT_SUPPORTED - If the event is published when no transaction is active, the listener is not called at all, unless it sets
.fallbackExecution = true
The request: pass values, not the request
The ScopeNotActiveException
// On the request thread: read what the background work needs
String tenantId = tenantContext.getTenantId(); // a request-scoped bean
Locale locale = LocaleContextHolder.getLocale();
receiptService.send(orderId, tenantId, locale);
@Async
public void send(long orderId, String tenantId, Locale locale) {
// uses the values it was given, on any thread
}
Copying the request itself to another thread, for example by capturing RequestContextHolder.getRequestAttributes()
Executors: set context in one place, and clear it
Passing values works well for a single method. When the same context must reach many tasks, such as the user's locale for every email sent in the background, one forgotten argument means text in the server's default language, as described earlier. A TaskDecorator
@Bean
TaskDecorator localeDecorator() {
return task -> {
// on the submitting thread: resolve the locale and time zone into plain values
LocaleContext context = new SimpleTimeZoneAwareLocaleContext(
LocaleContextHolder.getLocale(), LocaleContextHolder.getTimeZone());
return () -> {
// on the worker thread: set them, and restore what was there afterwards
LocaleContext previous = LocaleContextHolder.getLocaleContext();
LocaleContextHolder.setLocaleContext(context);
try {
task.run();
} finally {
LocaleContextHolder.setLocaleContext(previous);
}
};
};
}
The decorator resolves the locale into plain values before the task leaves the request thread. Copying LocaleContextHolder.getLocaleContext()
How the decorator reaches the executor depends on who creates the executor:
- Spring Boot combines every
bean, in order, and applies them to the task executor it configures, whichTaskDecorator uses by default.@Async - If the application defines its own executor bean, Spring Boot does not configure one, and the decorator must be set on that executor, for example with
. Alternatively,ThreadPoolTaskExecutor.setTaskDecorator makes Spring Boot create its own executor anyway, with the decorators applied.spring.task.execution.mode=force
Either way, the decorator applies to every task the executor runs, whether it comes from an @Asyncexecutesubmit
Spring Boot 4.1 also offers a ready-made option. With the Micrometer Context Propagation library on the classpath, setting spring.task.execution.propagate-context=trueContextPropagatingTaskDecorator
ContextRegistry.getInstance()
.registerThreadLocalAccessor(new LocaleContextThreadLocalAccessor());
With that in place, an @Async
CompletableFuture and parallel streams
In the earlier example, supplyAsync...AsyncCompletableFutureapplicationTaskExecutorsupplyAsync(supplier, executor)
Parallel streams split their work between the calling thread and the common pool, so request context is visible to only some elements, as the earlier example showed. The reliable fix is to read any request context before the stream starts and use local variables inside it.
Best practices
Clear what you set
Threads in a pool live for a long time and run many unrelated tasks. A value that one task sets and never removes is still there when the next task runs on the same thread:
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> { USER.set("alice"); log("task for alice"); }).get();
pool.submit(() -> log("task for bob")).get();
pool-1-thread-1: task for alice user=alice
pool-1-thread-1: task for bob user=alice
The second task runs with the first task's value. With request context, that means a tenant id, a locale or another value from an earlier request applied to the wrong work. Spring clears its own holders when a request or transaction ends. Context that application code sets on a worker thread needs the same treatment, which is why the decorator above restores the locale in a finally
Keep inheritable ThreadLocals away from thread pools
Java's InheritableThreadLocalRequestContextHolderLocaleContextHolderthreadContextInheritableDispatcherServlet
static final InheritableThreadLocal<String> INHERITED =
new InheritableThreadLocal<>();
ExecutorService pool = Executors.newFixedThreadPool(1);
INHERITED.set("alice");
pool.submit(() -> {}).get(); // the pool creates its thread, copying "alice"
INHERITED.set("bob"); // a later request on the same thread
pool.submit(() -> System.out.println("pooled thread sees " + INHERITED.get()))
.get();
Thread.ofVirtual()
.start(() -> System.out.println("new virtual thread sees " + INHERITED.get()))
.join();
pooled thread sees alice
new virtual thread sees bob
The pooled thread keeps the value it was created with, while a newly created thread sees the current one. The same code would therefore behave differently depending on whether the executor reuses threads. DispatcherServlet
Scoped values: an option for your own context
Java 25 made scoped values final (
A scoped value is bound for the duration of one call. The code that starts a piece of work binds it, and any code that runs inside that call can read it:
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
void serve() {
ScopedValue.where(TENANT, "acme").run(() -> handle()); // bound while handle() runs
}
void handle() {
System.out.println(TENANT.get()); // prints acme
}
Once runTENANT.get()NoSuchElementExceptionTENANT.isBound()
Scoped values do not solve the problem this guide is about. Like a ThreadLocal, a binding stays on the thread that made it, so it does not reach @AsyncTaskDecorator
static Runnable carryTenant(Runnable task) {
String tenant = TENANT.get(); // on the submitting thread
return () -> ScopedValue.where(TENANT, tenant).run(task); // on the worker thread
}
What scoped values change is safety on the thread where they are bound. The binding ends when the call returns, so there is nothing to clear, and no value can leak into the next task on a pooled thread. Code further down cannot change the value; it can only bind a new one for a call it makes. Subtasks started with structured concurrency, still a preview feature in Java 27, see the binding automatically.
Spring Framework 7 still keeps its own context in ThreadLocals. In an HandlerInterceptorpreHandle
So scoped values suit context that an application sets itself on Java 25 or later, such as a tenant id, in place of a ThreadLocal of its own. Bind them where a piece of work starts, in code that wraps all of it: a servlet filter around chain.doFilter
Summary
Keeping context on the request thread is what lets Spring manage transactions and request-scoped beans without any plumbing in application code. It also means that every hand-off to another thread is a decision about context:
- Spring keeps the current transaction, the current request and the locale in ThreadLocals on the thread that handles the request.
- Code that runs on another thread, through
,@Async , an executor or a parallel stream, starts without that context.CompletableFuture - A transaction should stay on its own thread. Background work should run in its own transaction and, when it needs the caller's data, start after the caller's transaction commits.
- Request data that background work needs is best read on the request thread and passed on as plain values.
- Pooled threads are reused, so context that a task sets should be cleared or restored when the task ends.
- When many tasks need the same context, a
, orTaskDecorator in Spring Boot 4.1, sets it in one place. Copy plain values, not objects that still read the request.spring.task.execution.propagate-context - Scoped values make an application's own context harder to leak or overwrite, but they do not cross threads either.
The same rules apply to other context kept the same way, such as Spring Security's security context, which propagate-context