Memory Visibility in Structured Concurrency: What fork() and join() Guarantee
The happens-before guarantees of StructuredTaskScope: owner writes before fork() are visible to subtasks, and a subtask's writes are visible once its outcome is read or feeds join(). What isn't covered: sibling subtasks sharing state, writes after fork(), and losers' side effects.
kvi5hnuCode Sprout team member7 min readOn this page
Subtasks run in other threads. In Java, a write in one thread isn't automatically visible to another: without a happens-before relationship between them, the reading thread may see a stale value, or a half-built object. Locks, volatile, Thread.start() and Thread.join() create such relationships, and so do java.util.concurrent classes such as Future and BlockingQueue.
StructuredTaskScope creates them too, along exactly the paths that structured code uses. If you pass data into subtasks through fork and get results out through handles or join(), you need no volatile fields and no locks.
The guarantees
The Java 27 StructuredTaskScope documentation specifies three happens-before edges:
- Owner to subtask. Everything the owner did before forking a subtask happens-before everything that subtask does.
- Subtask to reader. Everything a subtask did happens-before the actions of any thread that successfully obtains its outcome with
Subtask.get()orSubtask.exception(). - Subtask to
join(). If a subtask's outcome contributes to the result or exception fromjoin(), everything it did happens-before the owner returns fromjoin()with that outcome.

In practice
The program passes a mutable, non-thread-safe request object into three subtasks, lets each build a non-thread-safe result, and then shows a race between siblings. It uses the Java 27 preview API (java --enable-preview Visibility.java on Java 27, no flag on Java 28).
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.atomic.LongAdder;
public class Visibility {
/** A mutable, non-thread-safe request object: plain fields, an ArrayList. */
static final class SearchRequest {
String origin;
List<String> destinations = new ArrayList<>();
int maxPrice;
}
/** A mutable, non-thread-safe result built entirely inside one subtask. */
static final class FareTable {
final Map<String, Integer> fares = new HashMap<>();
int lookups;
}
static FareTable lookUpFares(SearchRequest request, String destination) {
FareTable table = new FareTable();
for (int day = 1; day <= 3; day++) {
table.fares.put(destination + " day " + day, request.maxPrice - 10 * day - destination.length());
table.lookups++;
}
return table;
}
static int unsafeCounter; // shared by sibling subtasks: a data race
public static void main(String[] args) throws Exception {
// 1. Owner writes before fork() are visible in the subtasks, without volatile or locks
SearchRequest request = new SearchRequest();
request.origin = "LIS";
request.destinations.addAll(List.of("OPO", "FAO", "MAD"));
request.maxPrice = 300;
// 2. Each subtask builds its own non-thread-safe result; the owner reads it after join()
try (var scope = StructuredTaskScope.open()) {
List<Subtask<FareTable>> tables = new ArrayList<>();
for (String dest : request.destinations) {
tables.add(scope.fork(() -> lookUpFares(request, dest)));
}
scope.join();
int lookups = 0, cheapest = Integer.MAX_VALUE;
for (Subtask<FareTable> t : tables) {
lookups += t.get().lookups;
for (int fare : t.get().fares.values()) cheapest = Math.min(cheapest, fare);
}
System.out.println("1+2. from " + request.origin + ": " + lookups + " lookups, cheapest fare " + cheapest);
}
// 3. Siblings writing the same plain field race with each other: no guarantee covers that
LongAdder safeCounter = new LongAdder();
try (var scope = StructuredTaskScope.open(Joiner.<Object>allSuccessfulOrThrow())) {
for (int i = 0; i < 4; i++) {
scope.fork(() -> {
for (int n = 0; n < 1_000_000; n++) {
unsafeCounter++; // read-modify-write on a shared plain int
safeCounter.increment();
}
});
}
scope.join();
}
System.out.println("3. expected 4000000; LongAdder: " + safeCounter.sum()
+ "; plain int lost updates: " + (unsafeCounter < 4_000_000));
}
}
Output (the last value depends on the race, but lost updates are almost certain with four threads and a million increments each):
1+2. from LIS: 9 lookups, cheapest fare 267
3. expected 4000000; LongAdder: 4000000; plain int lost updates: true
1. Into the subtasks
SearchRequest has plain fields and an ArrayList, and none of it is thread-safe. The owner filled it in before forking, so by edge 1 every subtask sees the complete object: the origin, all three destinations, the price limit. No volatile, no copying.
The guarantee covers what the owner did before each fork. If the owner changed request.maxPrice after forking, a running subtask might or might not see the change. Don't mutate shared input after forking. Better still, make it immutable: a record with List.copyOf fields cannot be changed by anyone.
2. Out of the subtasks
Each subtask built its own FareTable, a HashMap plus an int counter, and returned it. The owner read every table after join(), through Subtask.get(). By edge 2, all the subtask's writes to that table are visible: 9 lookups and the cheapest fare, computed from plain fields written in three other threads.
This is the pattern to prefer: each subtask owns what it builds, and hands it over by returning it. Nothing is shared while the subtasks run, so nothing needs synchronization.
3. Between siblings: no guarantee
Four sibling subtasks incremented the same static int. The scope gives no ordering between siblings, and unsafeCounter++ is a read, an add and a write. Concurrent increments overwrite each other, and updates are lost. The LongAdder, which is built for concurrent increments, counted exactly 4,000,000.
Visibility wasn't the problem there: the owner read both counters after join(), and edge 3 makes all four subtasks' writes visible. The problem was atomicity while they ran. Structured concurrency doesn't make shared mutable state safe. It only orders the hand-offs between owner and subtasks.
What isn't covered
| Situation | Guaranteed? | What to do |
|---|---|---|
Owner writes before fork, subtask reads | yes (edge 1) | nothing |
Owner writes after fork, subtask reads | no | don't. Pass data in at fork time, or use a thread-safe hand-off |
Subtask returns an object, owner reads it via get() | yes (edge 2) | nothing |
Subtask writes shared state, owner reads it after join() | yes, if the subtask's outcome contributed to join(), or the owner called get() or exception() on it | prefer returning results |
| Siblings write the same state while running | no | atomics, LongAdder, concurrent collections, locks |
| A cancelled subtask, or a race loser, wrote shared state | no ordering promised | don't rely on losers' side effects |
The last row matters for anySuccessfulOrThrow (article 30) and for timeouts. The winner's outcome feeds join(), so its writes are visible. A loser's outcome doesn't, so whatever it wrote to shared state before being cancelled has no happens-before edge to the owner. Use thread-safe structures for anything losers might touch, or better, have them write nothing shared.
Joiners and visibility
A custom joiner's onComplete runs in subtask threads, concurrently (article 33), so the joiner's fields are shared mutable state between siblings: the "Siblings write the same state while running" row applies. That's why joiners use atomics and concurrent queues. What result() reads from those thread-safe structures is then safely visible to the owner.
What's current
- The memory-consistency rules are part of the
StructuredTaskScopespecification in Java 27 (JEP 533) and Java 28 (JEP 543). Java 25's documentation stated only the first chain, from fork to the subtask toSubtask.get(). Java 27 extended it toexception()and to outcomes that feedjoin(). - They're in line with the rest of
java.util.concurrent. For example, actions before submitting a task to an executor happen-before the task runs, and the task's actions happen-beforeFuture.get()returns. - Scoped values bound when the scope is opened are inherited by the subtasks (article 41). That's another safe way to pass context in.
Common questions
Do I need volatile on fields that subtasks read?
Not if the owner set them before forking and nobody changes them afterwards. The fork creates the necessary happens-before edge.
Is a HashMap returned from a subtask safe to read after join()?
Yes, as long as nothing else modifies it. All of the subtask's writes happen-before the owner's successful get(), so the owner sees the complete map. Concurrent modification by other threads would still be a problem.
Doesn't close() waiting for all subtask threads make everything visible?
Don't rely on it. The specification defines the edges in terms of forking, obtaining outcomes, and join(). Use those paths, or thread-safe structures, for anything you read later.
Why did the plain counter lose updates if join() makes writes visible?
Visibility and atomicity are different problems. The owner saw the final value written, but while the subtasks ran, their read-add-write sequences interleaved and overwrote each other.
Summary
- Owner writes before
fork()are visible to the subtask. A subtask's writes are visible to whoever successfully reads its outcome, and to the owner afterjoin()if the outcome contributed. - Pass data in at fork time, and get results out by returning them from the subtask. Then no locks or
volatileare needed. - There's no ordering between sibling subtasks: shared mutable state needs atomics, adders, concurrent collections or locks.
- Writes after
fork(), and side effects of cancelled subtasks or race losers, have no guaranteed visibility.
Practice questions
The owner creates a List<String> with new ArrayList<>(), adds ten cities, forks five subtasks that read the list, and then adds an eleventh city. What does each subtask see?
Answer
All ten cities added before the forks, guaranteed. The eleventh may or may not be visible, and because ArrayList isn't thread-safe, a subtask reading while the owner adds could even see an inconsistent list. Finish building the input before forking, ideally as an immutable List.copyOf.
Three subtasks each append results to one shared ArrayList, and the owner prints it after join(). Is that correct?
Answer
No. The appends race with each other while the subtasks run, and ArrayList isn't safe for concurrent writes, so elements can be lost or the list corrupted. Either return each subtask's results and combine them in the owner, or use a concurrent collection such as ConcurrentLinkedQueue.
In a race with anySuccessfulOrThrow, the losing subtasks write timing statistics into a plain long[] array before they're cancelled. Can the owner rely on reading those values after join()?
Answer
No. Only the winner's outcome contributes to join(), so only its actions are guaranteed to happen-before the owner returns. The losers' writes have no happens-before edge to the owner. Use a thread-safe structure, such as an AtomicLongArray or a LongAdder, if losers must record anything.
Previous: Writing Custom Joiners in Java: Quorums, Collectors and Your Own Policies
Next: Nested Scopes in Java: Building Task Trees With StructuredTaskScope

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.