Passing Context in Java: Parameter Pollution and Why Thread-Locals Were Used
Request context such as a trace ID, tenant or currency must reach code deep in a call chain. Passing it as a parameter pollutes every signature; hiding it in a ThreadLocal cleans them up but adds hidden dependencies, nesting bugs and lost context across thread hand-offs.
kvi5hnuCode Sprout team member8 min readOn this page
Most server code needs data that isn't part of any method's job: the request's trace ID for logs, the tenant for data isolation, the user's currency or locale, a transaction or security principal. This is context. It's created at the edge, where the request arrives, and read deep inside, often in code the edge didn't write, such as a library or a framework callback.
Part 5 is about getting context from the first place to the second. This article covers the two traditional approaches and their problems. The next one looks at ThreadLocal's deeper flaws, and articles 40 and 41 replace it with scoped values.
Option 1: pass it as a parameter
The most honest approach is an explicit parameter. Every method on the path from the edge to the code that reads the context declares it, even methods that don't use it.

This works, and the compiler checks it. But it scales badly:
- Parameter pollution.
tax(amount, ctx)doesn't care about the trace ID. It takesctxonly so it can callaudit. Every layer between the edge and the reader carries framework data with no business meaning. - Brittle interfaces. When a second kind of context appears, say a feature-flag set, every signature on every path must change. If one of those methods implements a library or framework interface, you can't change it at all.
- Coupling. Business code now depends on framework types. Testing
taxmeans building aRequestContext, and moving the code to another framework means rewriting the signatures.
Option 2: a thread-local side channel
Because a request is usually handled by one thread from start to finish, frameworks have long used a ThreadLocal: a variable with a separate value for each thread. The framework sets the context before calling user code, user and framework code read it from anywhere on the same thread, and the framework removes it afterwards. Signatures go back to business parameters only.
This is how Java frameworks have worked for two decades. Spring's SecurityContextHolder, RequestContextHolder and transaction synchronization, SLF4J's MDC, and Jakarta EE's transaction and security contexts are all thread-locals underneath.
Both versions side by side
The program prices a trip with both versions, then shows three ways the thread-local version goes wrong.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public class Solution {
record RequestContext(String traceId, String tenant, String currency) {}
static final List<String> auditLog = new ArrayList<>();
// Version 1: the context is an explicit parameter of every method on the path
static class ExplicitQuotes {
String handle(String route, RequestContext ctx) {
int base = price(route, ctx);
return format(base + tax(base, ctx), ctx);
}
int price(String route, RequestContext ctx) {
audit("price " + route, ctx);
return route.length() * 37;
}
int tax(int amount, RequestContext ctx) { // needs ctx only to hand it on
audit("tax", ctx);
return amount / 10;
}
String format(int amount, RequestContext ctx) {
return amount + " " + ctx.currency();
}
void audit(String event, RequestContext ctx) {
auditLog.add("[" + ctx.traceId() + "/" + ctx.tenant() + "] " + event);
}
}
// Version 2: the framework keeps the context in a thread-local
static final class Context {
private static final ThreadLocal<RequestContext> CURRENT = new ThreadLocal<>();
static <T> T runWith(RequestContext ctx, Supplier<T> action) {
CURRENT.set(ctx);
try {
return action.get();
} finally {
CURRENT.remove(); // clean up for the next task on this thread
}
}
static RequestContext current() {
RequestContext ctx = CURRENT.get();
if (ctx == null) throw new IllegalStateException("no request context");
return ctx;
}
}
static class ImplicitQuotes {
String handle(String route) {
int base = price(route);
return format(base + tax(base));
}
int price(String route) {
audit("price " + route);
return route.length() * 37;
}
int tax(int amount) {
audit("tax");
return amount / 10;
}
String format(int amount) {
return amount + " " + Context.current().currency();
}
void audit(String event) {
RequestContext ctx = Context.current();
auditLog.add("[" + ctx.traceId() + "/" + ctx.tenant() + "] " + event);
}
}
static String attempt(Supplier<String> action) {
try {
return action.get();
} catch (IllegalStateException e) {
return "failed: " + e.getMessage();
}
}
public static void main(String[] args) throws Exception {
var lisbon = new RequestContext("t-101", "acme", "EUR");
var oslo = new RequestContext("t-102", "globex", "NOK");
System.out.println("1. explicit: " + new ExplicitQuotes().handle("LIS-OSL", lisbon));
ImplicitQuotes quotes = new ImplicitQuotes();
System.out.println("2. implicit: " + Context.runWith(oslo, () -> quotes.handle("OSL-TOS")));
auditLog.forEach(line -> System.out.println(" " + line));
// 3. Hidden dependency: calling a helper outside a request (as a unit test would)
System.out.println("3. tax alone: " + attempt(() -> String.valueOf(quotes.tax(100))));
// 4. Nesting: the inner runWith removes the context instead of restoring the outer one
System.out.println("4. nested: " + attempt(() -> Context.runWith(lisbon, () -> {
String inner = Context.runWith(oslo, () -> quotes.format(10));
return inner + ", then outer " + quotes.format(20);
})));
// 5. Hand-off: a task submitted to a pool runs on another thread, without the context
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
String result = Context.runWith(lisbon, () -> {
try {
return pool.submit(() -> attempt(() -> quotes.format(30))).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
System.out.println("5. pool task: " + result);
}
}
}
Output:
1. explicit: 284 EUR
2. implicit: 284 NOK
[t-101/acme] price LIS-OSL
[t-101/acme] tax
[t-102/globex] price OSL-TOS
[t-102/globex] tax
3. tax alone: failed: no request context
4. nested: failed: no request context
5. pool task: failed: no request context
Lines 1 and 2 produce the same quote and the same audit trail. The implicit version's signatures are cleaner: tax(int amount) says only what it needs. The cost shows up in lines 3 to 5.
3. Hidden dependencies
tax(100) looks like a pure calculation, but it calls audit, which needs a context. Called outside a request, as a unit test or a batch job would, it fails. With an explicit parameter, the compiler forces the caller to provide the context. With a thread-local, the dependency is invisible until run time.
4. Nesting is easy to get wrong
runWith sets the context and removes it in finally. That's the usual cleanup advice, but when a second runWith runs inside the first one, its finally removes the outer request's context too. The inner call worked, and then the outer code failed: then outer ... never printed. A correct version must save the previous value and restore it:
RequestContext previous = CURRENT.get();
CURRENT.set(ctx);
try {
return action.get();
} finally {
if (previous == null) CURRENT.remove(); else CURRENT.set(previous);
}
Every framework that nests contexts, such as transactions inside transactions or a "run as administrator" block, has to write and test this logic itself. Scoped values (article 40) restore outer bindings automatically.
5. Context doesn't follow the work
The task submitted to the pool ran on a pool thread, which has its own, empty thread-local slots. Any time work moves to another thread (executors, CompletableFuture.supplyAsync, parallel streams, structured subtasks), a thread-local context is lost unless something copies it. Frameworks add wrappers for this, such as Spring's TaskDecorator, the context-propagation libraries used by Micrometer and Reactor, and InheritableThreadLocal, which has its own problems (article 39).
Which to use
| Explicit parameter | ThreadLocal | |
|---|---|---|
| Clean business signatures | no | yes |
| Dependency visible to the compiler | yes | no |
| Nesting | trivial: pass a different argument | needs save-and-restore code |
| Crossing threads | the argument goes with the task | lost unless copied |
| Cleanup | none needed | remove() in finally, or leaks (article 39) |
For business data that a method really uses, explicit parameters are still the best choice. Context is the exception: data that is the same for a whole request and is needed by framework-level code at the edges of many call paths. That's where implicit passing pays off, and where Java 25's ScopedValue keeps the clean signatures while fixing the nesting and cleanup problems, and is inherited by structured subtasks. Unstructured hand-offs to executors still need explicit capture and rebinding.
What's current
ThreadLocalhasn't changed in recent releases. It works with virtual threads, at the memory cost described in article 15.java.lang.ScopedValueis final in Java 25 (JEP 506), after previews in Java 21 to 24, and is the recommended way to pass context in new code. Its API is the same in Java 26 and 27.- Frameworks are adopting scoped values gradually. Thread-local based APIs such as
MDCand Spring's context holders remain common and will be around for years.
Common questions
Isn't a thread-local just a global variable? Almost: a global variable with one value per thread. It shares globals' problems: anyone can read or write it, and nothing in a method's signature tells you it's used.
Why not put the context in a field of a request-scoped object? That works when every class that needs the context is created per request, for example by a DI container's request scope. Under the hood, request scope is usually implemented with a thread-local, and it doesn't help static helpers or library code.
Do lambdas capture thread-local values?
No. A lambda captures variables, not thread-local slots. If the lambda calls CURRENT.get(), it reads the value of whichever thread runs it, which is why the pool task in the demo saw nothing.
Is remove() in finally still important with virtual threads?
Less so for leaks, since each virtual thread runs one task and then dies. It's still essential for nesting correctness, and for any code that might run on pooled platform threads.
Summary
- Context such as trace IDs, tenants and transactions is created at the edge and read deep inside. Passing it explicitly pollutes every signature on the path and couples business code to framework types.
- A
ThreadLocallets the framework set the context once and read it anywhere on the same thread, keeping signatures clean. That's why frameworks have used it for decades. - The costs: hidden dependencies that fail at run time, nesting that needs save-and-restore code, and context that's lost whenever work moves to another thread.
- Scoped values (articles 40 and 41) keep implicit passing but fix nesting, cleanup and inheritance into structured subtasks.
Practice questions
A RequestContext parameter appears in 140 method signatures, but only 9 methods read it. What does that tell you, and what are the options?
Answer
131 methods carry it only to pass it on: classic parameter pollution. If it's genuinely request-wide context read by framework-level code (logging, auditing, security), implicit passing with a ScopedValue removes it from the signatures. If some methods use it as business data, keep explicit parameters for those, or pass just the field they need, such as the currency.
A framework's runAs(user, action) sets a thread-local, runs the action and calls remove() in finally. A user calls runAs(admin, ...) inside runAs(alice, ...). What's wrong after the inner call returns?
Answer
The inner finally removed the thread-local entirely, so the rest of the outer action runs with no user instead of alice. Depending on the code, that's a failure or a security bug. runAs must save the previous value and restore it in finally.
Code inside a request calls CompletableFuture.supplyAsync(() -> audit("cache miss")), and audit reads the trace ID from a thread-local. What happens?
Answer
The supplier runs on a ForkJoinPool.commonPool() thread, which doesn't have the request's thread-local value. audit finds no context: it logs without a trace ID, throws, or, worse, sees a stale value left behind by an earlier task on that pool thread. The context has to be captured and reinstalled on the other thread explicitly.
Previous: StructuredTaskScope From Java 21 to Java 28: Every API Change and How to Migrate
Next: The Problems With ThreadLocal in Java: Mutability, Leaks and InheritableThreadLocal

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.