Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What is Structured Concurrency and Scoped Values in Java 21+?
senior LevelCode ExampleSystem Design
In Simple Words:
Structured Concurrency treats multiple tasks running in separate threads as a single unit of work, ensuring that child threads never outlive their parent scope. Scoped Values provide a safe, immutable alternative to ThreadLocal for sharing data across millions of virtual threads.
The Problem with Unstructured Concurrency:
In classic Java, if one subtask fails or times out, sibling threads continue running in the background as orphaned "thread leaks", consuming CPU, memory, and database sockets.
java
// Structured Concurrency in Java 21+ (Preview):
Response handleRequest() throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<User> userTask = scope.fork(() -> fetchUser());
Supplier<Order> orderTask = scope.fork(() -> fetchOrder());
scope.join(); // Join both concurrent subtasks
scope.throwIfFailed(); // Propagate exception if either subtask failed!
return new Response(userTask.get(), orderTask.get());
} // Both virtual threads are guaranteed to be closed here!
}