Files
javademos/lanes/src/StructuredHub.java

38 lines
1.7 KiB
Java

import java.util.concurrent.StructuredTaskScope;
/**
* The structured concurrency example from ankurm.com/java-21-to-25-lts-features. JEP 505 in Java 25 is the FIFTH
* PREVIEW, not a final feature: without --enable-preview javac refuses, on 25, 26 and 27 alike.
* Chapter: docs/14-lanes-21-to-25.md
*/
public class StructuredHub {
record Dashboard(String user, String order) {}
static String fetchUser(int id) throws InterruptedException { Thread.sleep(20); return "user-" + id; }
static String fetchOrder(int id) throws InterruptedException { Thread.sleep(30); return "order-for-" + id; }
static Dashboard fanOut(int userId) throws Exception {
try (var scope = StructuredTaskScope.open()) {
var user = scope.fork(() -> fetchUser(userId));
var order = scope.fork(() -> fetchOrder(userId));
scope.join();
return new Dashboard(user.get(), order.get());
}
}
static String firstSuccess() throws Exception {
try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> { Thread.sleep(200); return "slow"; });
scope.fork(() -> "fast");
return scope.join();
}
}
public static void main(String[] args) throws Exception {
System.out.println("java.version = " + System.getProperty("java.version"));
Dashboard d = fanOut(7);
Check.that(d.equals(new Dashboard("user-7", "order-for-7")), "fan-out: both results joined: " + d);
Check.that(firstSuccess().equals("fast"), "anySuccessfulResultOrThrow(): the first result wins and the slow subtask is cancelled");
}
}