Video in progress

Strong Middle 🧱 OOP and SOLID

What design risks come from passing context such as the user, tenant or trace ID through a `ThreadLocal`?

ThreadLocal is hidden global state: a dependency appears that isn't visible in the method signature. In a thread pool, if you don't clear it, the context "leaks" into the next request, and in async code it simply disappears. It's fine for small cross-cutting data (a trace ID), not for business data.

📖 Answer

Spring itself relies on ThreadLocal: SecurityContextHolder, TransactionSynchronizationManager, RequestContextHolder, SLF4J MDC. So as a tool it isn't bad. The problem starts when you use it for business logic.

A typical bug:

public class TenantContext {
    private static final ThreadLocal<String> TENANT = new ThreadLocal<>();
    public static void set(String t) { TENANT.set(t); }
    public static String get() { return TENANT.get(); }
}

// set in a filter, but remove() was forgotten in finally

The Tomcat thread takes the next request from a different customer, and works with the old tenant. That is a data leak. Always:

try { TenantContext.set(t); chain.doFilter(req, res); }
finally { TenantContext.clear(); }

Other problems:

  • @Async, CompletableFuture.supplyAsync, Reactor: a different thread, no context. You need a TaskDecorator or Micrometer context propagation;
  • a hidden TenantContext.get() inside PricingService.calculate(order): it's easy to forget to set it in a test, and the method signature tells you nothing;
  • ThreadLocal works with virtual threads (Java 21), but with a million threads it has a memory cost. That's why ScopedValue was added (a preview in Java 21).

My rule: a value that changes a domain decision (tenant, currency, user permissions) is passed explicitly, as a parameter or a context object. For observability (trace ID, log context), ThreadLocal/MDC is fine.