Sub topic 1
Why context is hard to share across method calls
Prerequisites
This chapter assumes you know the following:
- Core Java syntax, including lambdas and functional interfaces.
- How threads and the call stack work at a basic level.
- Static fields and the
finalkeyword.
Familiarity with ThreadLocal helps, but you don't need it. The next chapter covers it in detail.
The problem: data that every layer needs
Most server applications handle many requests at once. Each request carries data that many layers of code need: the current user, a request ID for logging, a tenant name, or a security token. This data is context. It belongs to the whole request, not to any one method.
Suppose a request enters through a controller. The controller calls a service. The service calls a repository. The repository writes an audit log that needs the user's name. Only the last method uses the data, but the earlier methods must still carry it.
Option 1: pass it as a parameter
The plainest approach is to add a parameter to every method on the path.
public class ExplicitContext {
static void controller(String user) {
service(user);
}
static void service(String user) {
repository(user);
}
static void repository(String user) {
System.out.println("Audit: saved by " + user);
}
public static void main(String[] args) {
controller("alice");
}
}This is clear and easy to test. The cost shows up as the code grows:
- Every method on the path needs the extra parameter, even if it never reads it.
- Adding a second piece of context, such as a request ID, changes every signature again.
- Code you don't own, such as a framework callback or an interface method, has a fixed signature. You can't add a parameter to it.
Option 2: store it somewhere shared
To avoid the extra parameters, you could put the context in a place every method can reach. A plain static field is shared by all threads, so two simultaneous requests would overwrite each other's user.
public class SharedStatic {
static String currentUser; // one value for the whole JVM
public static void main(String[] args) {
currentUser = "alice";
// Another request thread could set currentUser = "bob" right now,
// and this code would then read the wrong user.
System.out.println("Handling " + currentUser);
}
}What you want is a value that is shared across method calls but separate for each request. Java's older answer is ThreadLocal, which gives each thread its own copy. It works, but it has problems of its own, covered in the next chapter.
What an ideal solution needs
A good mechanism for implicit context has these properties:
- Visible to callees. Any method called from the entry point can read the value without a parameter.
- Isolated per request. Concurrent requests never see each other's values.
- Bounded. The value exists only while the entry-point code runs. It can't leak past that.
- Safe to read. Code deep in the call chain can read the value but can't change it for its callers.
ScopedValue, the subject of this tutorial, is built to meet these four properties. You will declare one, bind it, and read it in the chapters that follow.
Exercise
Exercise
A static field static String currentUser is set at the start of each request, and the server handles requests on many threads at once. Which of the four properties does this design violate, and what can go wrong?
Show answer
It violates isolation per request. All threads share the one static field, so a second request can overwrite the user while the first is still running. The first request's code then reads the wrong user, which can cause incorrect audit entries or access to another user's data.
Exercise
Name two drawbacks of passing context as a method parameter through every layer.
Show answer
Every method on the call path needs the extra parameter even if it doesn't use it, and each new piece of context changes many signatures. Framework callbacks and interface methods with fixed signatures can't take the extra parameter at all.