Observing Structured Concurrency: Scope Names, Thread Dumps and Task Trees
Structured concurrency makes the task tree visible. Name scopes with withName and subtask threads with a ThreadFactory, take JSON thread dumps with jcmd or HotSpotDiagnosticMXBean, read containers, parents and owners, and capture a dump automatically when an operation fails or stalls.
kvi5hnuCode Sprout team member7 min readOn this page
With unstructured concurrency, a thread dump of a busy service is a flat list of thousands of threads, and nothing says which ones belong together (article 26). Structured concurrency changes that. Each StructuredTaskScope is a thread container that the JVM knows about, with an owner and a parent. A JSON thread dump prints those containers as a tree, so you can see each request, its subtasks, and their subtasks.
What the dump contains
Article 17 introduced JSON thread dumps:
jcmd <pid> Thread.dump_to_file -format=json /tmp/threads.json
The file lists threadContainers. For a scope, a container entry has:
container: the scope's name (fromwithName), followed by an internal class name and identity hash. An unnamed scope shows only the internal part, such asjava.util.concurrent.StructuredTaskScopeImpl@4554617con JDK 25.parent: the enclosing container. For a nested scope that's the outer scope. For a top-level scope it's the container of the owner thread:<root>formainor a thread started directly, or the executor's container when the owner is a pooled or per-task request thread.owner: the thread ID of the scope's owner.threads: each subtask thread with its name, state and stack.
Here's one container from a real dump, trimmed to its first thread:
{
"container": "flight-legs/jdk.internal.misc.ThreadFlock$ThreadContainerImpl@241c47b2",
"parent": "trip/jdk.internal.misc.ThreadFlock$ThreadContainerImpl@1f91f0e7",
"owner": "27",
"threads": [
{
"tid": "32",
"virtual": true,
"name": "leg-0",
"state": "TIMED_WAITING",
"stack": [
"java.base/java.lang.VirtualThread.parkNanos(VirtualThread.java:787)",
"...",
"TaskTree.call(TaskTree.java:21)",
"TaskTree.lambda$flights$1(TaskTree.java:29)",
"java.base/java.util.concurrent.StructuredTaskScopeImpl$SubtaskImpl.run(StructuredTaskScopeImpl.java:325)",
"java.base/java.lang.VirtualThread.run(VirtualThread.java:460)"
]
}
],
"threadCount": "3"
}
Without names, this would say StructuredTaskScopeImpl@... and "name": "", which is correct but much less helpful in a dump with 500 requests.
Reading the tree from a dump
The program runs a two-level trip (as in article 35) with named scopes and named subtask threads, takes a JSON dump of itself while all subtasks are blocked, and prints each scope with its parent, owner and threads. It uses the Java 27 preview API (java --enable-preview TaskTree.java on Java 27, no flag on Java 28).
import com.sun.management.HotSpotDiagnosticMXBean;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TaskTree {
static final CountDownLatch allRunning = new CountDownLatch(4); // 3 legs + hotel
static String call(String what) throws InterruptedException {
allRunning.countDown();
Thread.sleep(1000);
return what;
}
static List<String> flights() throws Exception {
var legThreads = Thread.ofVirtual().name("leg-", 0).factory();
try (var legs = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withName("flight-legs").withThreadFactory(legThreads))) {
for (String leg : List.of("LIS-AMS", "AMS-OSL", "OSL-TOS")) legs.fork(() -> call(leg));
return legs.join();
}
}
/** Takes a JSON thread dump of this JVM while the scopes are running. */
static Path dumpWhenBusy() throws Exception {
allRunning.await();
Path file = Files.createTempFile("trip-dump", ".json");
Files.delete(file); // dumpThreads refuses to overwrite
ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
.dumpThreads(file.toAbsolutePath().toString(), HotSpotDiagnosticMXBean.ThreadDumpFormat.JSON);
return file;
}
public static void main(String[] args) throws Exception {
Thread.currentThread().setName("request-42");
Path[] dump = new Path[1];
Thread dumper = Thread.ofPlatform().start(() -> {
try { dump[0] = dumpWhenBusy(); } catch (Exception e) { throw new RuntimeException(e); }
});
var tripThreads = Thread.ofVirtual().name("trip-", 0).factory();
try (var trip = StructuredTaskScope.open(Joiner.awaitAllSuccessfulOrThrow(),
cf -> cf.withName("trip").withThreadFactory(tripThreads))) {
trip.fork(TaskTree::flights);
trip.fork(() -> call("hotel"));
trip.join();
}
dumper.join();
printScopes(Files.readString(dump[0]));
Files.delete(dump[0]);
}
/** A tiny reader for the dump: container name, parent, owner and thread names (no JSON library needed). */
static void printScopes(String json) {
Map<String, String> threadNames = new HashMap<>();
Matcher t = Pattern.compile("\"tid\": \"(\\d+)\",[^}]*?\"name\": \"([^\"]*)\"").matcher(json);
while (t.find()) threadNames.put(t.group(1), t.group(2));
List<String> lines = new ArrayList<>();
for (String block : json.split("\"container\": ")) {
Matcher c = Pattern.compile("^\"([^/\"]+)/[^\"]*\",\\s*\"parent\": \"([^/\"]+)[^\"]*\",\\s*\"owner\": \"(\\d+)\"").matcher(block);
if (!c.find()) continue; // only containers with an owner: scopes
TreeSet<String> names = new TreeSet<>();
Matcher n = Pattern.compile("\"name\": \"([^\"]*)\"").matcher(block);
while (n.find()) names.add(n.group(1));
String name = c.group(1).replace("\\", ""), parent = c.group(2).replace("\\", ""); // JSON may escape '/'
lines.add("scope " + name + " (parent " + parent + ", owner " + threadNames.get(c.group(3))
+ "): threads " + names);
}
lines.forEach(System.out::println);
}
}
Output:
scope trip (parent <root>, owner request-42): threads [trip-0, trip-1]
scope flight-legs (parent trip, owner trip-0): threads [leg-0, leg-1, leg-2]

The dump reproduced the code's structure: trip is owned by the request thread, flight-legs is nested in trip and owned by trip-0, the subtask running flights(). Each subtask thread's stack shows exactly where it was waiting.
The regular-expression reader is only there to keep the demo dependency-free. Real tools should parse the file with a JSON library. The format has fields that a regex would easily trip over, such as escaped / characters in names, which the demo has to strip.
Naming conventions that pay off
- Name scopes after the operation, not the class:
trip,flight-legs,price-check. Names don't need to be unique. Use the same name for every instance of an operation, so you can count how many are running. - Name subtask threads with a numbered builder,
Thread.ofVirtual().name("leg-", 0).factory(), passed withwithThreadFactory. Thread names show up in dumps, logs, profilers and exception messages. - Keep the request ID out of thread names if it's sensitive or high-cardinality. Put it in a scoped value or a logging context (Part 5) instead.
Capturing a dump when something goes wrong
A dump is most useful at the moment of trouble. Two patterns:
On timeout or failure. When join() throws, the scope's subtasks have been cancelled, so a dump taken in the catch block is too late to see them. Instead, take it while they're still running: for a deadline, from a separate watchdog thread just before it expires, or simply in the handler of a slow-request alert. The HotSpotDiagnosticMXBean.dumpThreads call from the demo works in-process. It needs an absolute path to a file that doesn't exist yet.
From outside. For a stuck service, jcmd <pid> Thread.dump_to_file -format=json <file> needs no code changes. Run it two or three times a few seconds apart. Subtasks whose stacks don't change between dumps are the stuck ones, and the container tree tells you which operation they belong to.
Remember that jcmd <pid> Thread.print, the classic text dump, leaves out virtual threads. Use Thread.dump_to_file.
Other tools
- JFR records virtual-thread events (
jdk.VirtualThreadStart,jdk.VirtualThreadEnd,jdk.VirtualThreadPinned) and the usual I/O and lock events, with thread names (article 16). It has no scope-specific events, so named threads are how you connect JFR data to scopes. - Logs: include the thread name in the log pattern. With named subtask threads, interleaved log lines from concurrent subtasks are easy to tell apart.
- Debuggers: IDE debuggers such as IntelliJ IDEA can show virtual threads. How they present scopes varies by IDE and version, so check your IDE's documentation.
What's current
- JSON thread dumps with thread containers have been available since Java 21. Java 25 dumps also include each thread's
stateand lock information (article 17). withNameis part of the Java 25 to Java 28 scope configuration (article 32). In the Java 21 to 24 API, scopes were named through their constructor.- The internal class names in the
containerfield (ThreadFlock$ThreadContainerImpl,StructuredTaskScopeImpl) are implementation details and may differ between releases. Match on the name you gave the scope, not on the suffix.
Common questions
Does naming scopes or threads cost anything? Very little: a string per scope and per thread. It's worth it in any code that runs in production.
Why does the owner field contain a number instead of a name? It's the owner's thread ID. Look it up among the dump's threads (the demo builds a map from ID to name) to find the owner's name and stack.
Can I see the tree without a dump? Not through a public API. The thread-container tree is internal. JSON thread dumps, and tools built on them, are the supported way to see it.
Do executors show up in the dump too?
Yes, as flat containers such as java.util.concurrent.ThreadPerTaskExecutor@..., without the request structure. Only structured scopes give each operation its own nested container with an owner.
Summary
- Every
StructuredTaskScopeis a thread container. JSON thread dumps show each scope with its name, parent, owner and subtask threads, forming the task tree. - Name scopes with
withNameand subtask threads with a namedThreadFactory, so dumps, logs and profilers are readable. - Use
jcmd <pid> Thread.dump_to_file -format=json(notThread.print) orHotSpotDiagnosticMXBean.dumpThreadswith an absolute path. - Take dumps while subtasks are still running: repeated dumps reveal stuck subtasks and the operation they belong to.
Practice questions
A JSON dump shows 300 containers named java.util.concurrent.StructuredTaskScopeImpl@..., each with two threads whose names are empty. What would you change to make the next dump useful?
Answer
Name the scopes with cf -> cf.withName("quote") (or whatever operation they represent) and give subtasks named threads with withThreadFactory(Thread.ofVirtual().name("quote-", 0).factory()). The dump will then show 300 quote containers whose threads say what they are.
Why is a thread dump taken inside catch (ExecutionException e) after join() usually not helpful for finding a slow subtask?
Answer
By the time join() throws, the scope has been cancelled: the other subtasks have been interrupted and are finishing or finished, so the dump no longer shows where they were stuck. Take the dump while they're still running, from a watchdog thread or from outside with jcmd.
In a dump, container flight-legs has "owner": "27". How do you find out which code owns it?
Answer
Find the thread with "tid": "27" in the dump, usually in the parent container. Its name and stack show which subtask opened flight-legs and where it's waiting, typically in join().
Previous: Nested Scopes in Java: Building Task Trees With StructuredTaskScope
Next: StructuredTaskScope From Java 21 to Java 28: Every API Change and How to Migrate

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.