Sub topic 1
Why context is hard to share across method calls
Most programs carry some data that many methods need but only a few create. Examples are the authenticated user, a request ID for log correlation, a tenant, a locale, or a transaction handle. This chapter shows why that data is awkward to share. It also shows what each common workaround costs, so the rest of the tutorial has a problem to solve.
Prerequisites
This chapter assumes you already know:
- Core Java syntax, including lambdas, records, and functional interfaces such as
Runnable. - What a thread is, and that each thread has its own call stack.
- What
staticandfinalmean on a field. ThreadLocalat a basic level. This is helpful but not required.
The examples compile on Java 17 or later and use only the standard library.
What "context" means here
Context is data that is true for the whole of one unit of work, such as one HTTP request or one background job. It has three properties:
- Many methods at different depths of the call stack need to read it.
- It is set once, near the entry point, and should not change underneath the callee.
- It belongs to this unit of work only. Another request running at the same time has different values.
The following diagram shows the typical shape. Only the entry point knows the user, but the audit logger at the bottom needs it.
OrderService and OrderRepository have no use for the user themselves. They sit between the place that knows the value and the place that needs it.
Option 1: pass it as a parameter
The most direct approach is to add the context to every method signature along the path.
public class ParameterThreading {
record RequestContext(String user, int requestId) {}
public static void main(String[] args) {
handle(new RequestContext("alice", 42));
}
static void handle(RequestContext ctx) {
System.out.println("Handling request " + ctx.requestId());
loadOrders(ctx);
}
static void loadOrders(RequestContext ctx) {
query(ctx, "SELECT * FROM orders");
}
static void query(RequestContext ctx, String sql) {
audit(ctx, sql);
}
static void audit(RequestContext ctx, String action) {
System.out.println(ctx.user() + " #" + ctx.requestId() + ": " + action);
}
}This is explicit, type-checked, and easy to test. It is also the baseline every alternative is measured against. Its costs show up as the code grows:
- Signature noise.
loadOrdersandquerytakectxonly to forward it. Every intermediate method carries a parameter it does not use. - Change amplification. If
auditlater needs a tenant ID, you add a field to the record. That is cheap. If a method deep in the stack newly needs context, every caller up the chain needs a signature change. - Barriers you do not control. Callbacks, framework hooks, interface methods, and library code cannot take your extra parameter. A
Comparator, aRunnable, or a servlet filter has a fixed signature.
Parameter passing is still the right choice when only one or two layers need the data. The problem appears when the path is deep or crosses code you do not own.
Option 2: a static field
To avoid threading a parameter, you could store the context in a static field that anyone can read.
public class SharedFieldBug {
static volatile String currentUser;
static void handle(String user) {
currentUser = user;
pause();
System.out.println("Request for " + user + " sees " + currentUser);
}
static void pause() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> handle("alice"));
Thread b = new Thread(() -> handle("bob"));
a.start();
b.start();
a.join();
b.join();
}
}With one request at a time this works. With two concurrent requests, one thread overwrites the field while the other is still using it. On a typical run, both lines print the same name, and one of them is wrong. Making the field volatile fixes visibility between threads. It does not fix the fact that two unrelated requests share a single slot.
The root cause is that a static field has one value for the whole JVM, while context has one value per unit of work. A lock would not help, because it would force requests to run one at a time.
Option 3: one slot per thread
If each request runs on its own thread, a per-thread slot matches the shape of the data. That is the idea behind ThreadLocal.
public class ThreadLocalContext {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> handle("alice"));
Thread b = new Thread(() -> handle("bob"));
a.start();
b.start();
a.join();
b.join();
}
static void handle(String user) {
USER.set(user);
try {
report();
} finally {
USER.remove();
}
}
static void report() {
System.out.println("Working for " + USER.get());
}
}Each thread now sees its own value, and report() needs no parameter. This is why ThreadLocal became the standard answer, and why frameworks use it for security contexts, transactions, and logging identifiers.
It also trades one set of problems for another. Chapter 2 examines them in detail. The short version is:
- The value is mutable, and any code on the thread can call
setat any time. A reader cannot tell who changed it. - Its lifetime is not tied to any block of code. You must remember
remove()in afinally. If you forget, the value outlives the request. On pooled threads, the next request can then see a stale user. - Child threads may copy the value through
InheritableThreadLocal. That copying costs memory per thread and creates more stale-data risk. - Per-thread storage assumes threads are few and long-lived. That assumption weakens when a program creates very large numbers of virtual threads.
Comparing the three approaches
| Approach | Visible without passing a parameter | Safe with concurrent requests | Lifetime is bounded by code structure | Value can be changed by callees |
|---|---|---|---|---|
| Method parameter | No | Yes | Yes, the call itself | Depends on the type |
| Static field | Yes | No | No | Yes |
| `ThreadLocal` | Yes | Yes, per thread | No, you must call `remove()` | Yes |
The table shows the gap. We want something that is as convenient as ThreadLocal, as safe as a parameter, and whose lifetime ends when the block that set it ends.
What the solution looks like
A scoped value is that kind of construct. You declare it once, bind a value for the duration of a call, and read it anywhere beneath that call. Here is a first look. Later chapters explain each piece.
public class RequestContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> handle());
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}handle() takes no parameter and no one calls set. When the run call returns, the binding ends automatically, so there is nothing to clean up.
Design questions to ask about any context
Before choosing a mechanism, check the data against these questions:
- How many layers of code need it? One or two layers favor a plain parameter.
- Do you control every signature on the path? If not, parameters cannot reach the code that needs the data.
- Should callees be able to change it? Shared context is easier to reason about when they cannot.
- When should it stop existing? Context tied to a request should vanish when the request code finishes, without relying on a cleanup call.
- How many threads will carry it? This matters once you create threads in large numbers.
The rest of the tutorial answers these questions for scoped values, one concept at a time.
Exercise
A web handler stores the logged-in user in a static volatile String currentUser field so that deep helper methods can read it without a parameter. Two requests are served at the same time on different threads. Explain what can go wrong, and why adding volatile does not prevent it.
Show answer
The field holds one value for the whole JVM, but each request needs its own value. If request A sets the field and request B then overwrites it, A's helper methods read B's user, so A may log or authorize the wrong person. volatile only guarantees that writes are visible to other threads. It does not give each request a separate slot, so the overwrite still happens. The context must be stored per unit of work, for example as a parameter, in a ThreadLocal, or in a scoped value.
Exercise
Name two reasons that passing a context object as a method parameter becomes awkward in a large application, and name one situation where it is still the best choice.
Show answer
First, intermediate methods must accept and forward a parameter they never use, so adding a new context field or a new consumer deep in the stack changes many signatures. Second, code you do not control, such as callbacks, interface methods, or framework hooks, has a fixed signature and cannot take the extra parameter. Parameter passing is still the best choice when only one or two layers need the data, because it is explicit, type-checked, and easy to test.