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.

Janardhan Chejarla
Share

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 @Async methods, CompletableFuture, executors (Spring's own or plain Java ones) and parallel streams. None of these passes the request's context to the threads they use unless the application does so explicitly.

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 Callable or DeferredResult hand the request thread back as soon as they return. Their result is produced later on a different thread, and Spring writes the response once it is ready. Spring WebFlux passes request context through the exchange and the Reactor context rather than ThreadLocals. Both are outside the scope of this guide.

Because one thread handles the whole request, that thread is a convenient place to keep information about it. Java provides the mechanism: a ThreadLocal is a variable whose value belongs to the current thread. Each thread sees its own value, and a new thread starts with none.

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 useWhat it needsWhere Spring keeps it
@Transactional methods, JdbcTemplate, Spring Data JPA repositoriesThe current transaction and its database connectionTransactionSynchronizationManager
Request-scoped and session-scoped beansThe current HTTP requestRequestContextHolder
Localized validation messages, date and number formattingThe user's locale and time zoneLocaleContextHolder

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. DispatcherServlet binds the request and the locale when a request arrives and restores the previous values when the request completes. Spring Boot also registers a RequestContextFilter, which does the same for the request earlier in the filter chain.

This is why a method annotated with @Transactional can call several repositories that all share one connection, and why a request-scoped bean always holds the current request's data. Nothing is passed between the methods; each one finds the context on its thread.

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:

ApproachWhere the work runsRequest context available by default
@Async with Spring Boot's defaultsA pool with 8 core threads, or a new virtual thread per task when virtual threads are enabledNone
CompletableFuture.supplyAsync(...) without an executorForkJoinPool.commonPool()None
Your own ExecutorServiceThe executor's threadsNone
parallelStream()The calling thread and the common poolOnly 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(), looks up the request on the current thread. On another thread there is none. For a request-scoped bean, here one named tenantContext that holds the current tenant, Spring reports that the scope is not active, and the underlying cause names the likely reason (shortened here):

Text
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 @Async method returns void, the caller never sees this exception. Spring's default handler for asynchronous errors logs it at ERROR level instead.

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() falls back to a default locale, which is the JVM's unless the application sets its own, so text formatted on another thread can use a different language from the one the user asked for, without any error. A confirmation email built in the background, for example, may come out in the server's language rather than the user's.

All of this follows from how ThreadLocals work in plain Java, so it can be shown without Spring. The examples below use one ThreadLocal, USER, standing in for request context, and a small log helper that prints the thread's name and the value that thread sees. They were run on Java 21 with the common pool set to 7 workers, its default size on an 8-core machine.

Java
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:

Java
ExecutorService pool = Executors.newFixedThreadPool(1);
USER.set("alice");
log("request thread");
pool.submit(() -> log("pool task")).get();
Text
main: request thread                           user=alice
pool-1-thread-1: pool task                     user=null

So does CompletableFuture without an executor:

Java
USER.set("alice");
log("request thread");
CompletableFuture.supplyAsync(() -> { log("supplyAsync"); return 1; }).get();
Text
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:

Java
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"));
Text
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 method directly, that method may run before the order is committed and find nothing, as described earlier. Background work like this should start only after the caller's transaction has committed, and run in a transaction of its own.

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:

Java
@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:

  • @Async needs @EnableAsync on a configuration class. Spring Boot does not switch it on by itself.
  • If the listener writes to the database, give it its own transaction with @Transactional(propagation = Propagation.REQUIRES_NEW). The caller's transaction has already finished, so there is nothing to join. Spring allows only REQUIRES_NEW or NOT_SUPPORTED here; with any other propagation, the application fails to start.
  • 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 shown earlier comes from reading a request-scoped bean on a thread that has no request. Background work rarely needs the request itself, though, only a few values from it, such as a tenant id or the user's locale. A simple and safe fix is to read those values on the request thread and pass them as method arguments:

Java
// 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);
Java
@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() and setting it on the worker thread, is tempting but fragile. When a request completes, Spring marks its attributes as no longer active, and reading a request attribute after that fails with "Cannot ask for request attribute - request is not active anymore!". Background work can easily outlive the request that started it.

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 sets the context in one place instead. A decorator is called on the submitting thread, so it can read the current values, and it wraps the task so the worker thread sets them before running it and restores the previous values afterwards. This one passes the locale and time zone on:

Java
@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() itself is not enough: in a web application, the context Spring binds can read the locale from the request each time it is asked, so the worker thread would read a request that may already have finished. Restoring the previous context, rather than clearing it, also keeps the request thread's locale intact if a task ever runs on the thread that submitted it.

How the decorator reaches the executor depends on who creates the executor:

  • Spring Boot combines every TaskDecorator bean, in order, and applies them to the task executor it configures, which @Async uses by default.
  • 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 ThreadPoolTaskExecutor.setTaskDecorator. Alternatively, spring.task.execution.mode=force makes Spring Boot create its own executor anyway, with the decorators applied.

Either way, the decorator applies to every task the executor runs, whether it comes from an @Async method or from a direct call to execute or submit.

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=true adds Spring's ContextPropagatingTaskDecorator to the executor Spring Boot configures. It copies every ThreadLocal value that has an accessor registered with that library, and restores the worker thread's previous values after the task. Spring Security registers an accessor for its security context automatically, so the current user is carried across with no extra code. Spring Framework provides accessors for the locale and for request attributes, but registers neither. The locale accessor is registered like this:

Java
ContextRegistry.getInstance()
    .registerThreadLocalAccessor(new LocaleContextThreadLocalAccessor());

With that in place, an @Async method sees the request's locale without a hand-written decorator. One caution: the accessor copies the bound locale context as it is, which in a web application may still read the locale from the request. For work that can outlive the request, the decorator above, which copies plain values, is the safer choice.

CompletableFuture and parallel streams

In the earlier example, supplyAsync saw no value because, without an executor, the ...Async methods of CompletableFuture run on the common pool, which no Spring decorator reaches. To bring them under the same decorators, pass the executor that Spring Boot configures (the applicationTaskExecutor bean) as the extra argument, as in supplyAsync(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:

Java
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> { USER.set("alice"); log("task for alice"); }).get();
pool.submit(() -> log("task for bob")).get();
Text
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 block.

Keep inheritable ThreadLocals away from thread pools

Java's InheritableThreadLocal copies a value to a new thread, and RequestContextHolder and LocaleContextHolder use one when the threadContextInheritable property of DispatcherServlet is switched on. It looks like a way to carry context into background work, but the copy happens only when a thread is created. A pool creates its threads once and then reuses them:

Java
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();
Text
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 leaves inheritance switched off by default, "to avoid side effects on spawned background threads", as its documentation puts it.

Scoped values: an option for your own context

Java 25 made scoped values final (JEP 506). The JEP describes them as easier to reason about than ThreadLocals, and cheaper, especially with virtual threads. This section explains what they change for the problem in this guide, and what they do not.

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:

Java
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 run returns, the value is gone. Calling TENANT.get() outside a binding throws NoSuchElementException, and TENANT.isBound() checks first.

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 @Async methods or executor tasks. Carrying a value into another thread takes the same kind of wrapper as the TaskDecorator above, which reads the value on the submitting thread and binds it again inside the task:

Java
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 issue discussion, a Spring team member said there is no clear path from ThreadLocals to scoped values, and gave one reason: a HandlerInterceptor cannot bind a scoped value, because preHandle returns before the handler runs and the binding would end with it. Asked again after Java 25 made scoped values final, he said Spring should not add new contracts until there is a clearer vision and concrete use cases.

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, a message listener, or a scheduled job.

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, CompletableFuture, an executor or a parallel stream, starts without that context.
  • 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 TaskDecorator, or spring.task.execution.propagate-context in Spring Boot 4.1, sets it in one place. Copy plain values, not objects that still read the request.
  • 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 carries automatically, and the logging context that carries trace ids.

References