|
| 1 | +/* |
| 2 | + * Structured Concurrency Example in Java 25 |
| 3 | + * |
| 4 | + * This example demonstrates Java's StructuredTaskScope, a preview feature in Java 25. |
| 5 | + * Structured concurrency allows you to fork multiple tasks within a scope, wait for all |
| 6 | + * of them to complete, and handle exceptions in a structured way. |
| 7 | + * |
| 8 | + * Key points: |
| 9 | + * 1. Tasks are forked concurrently using scope.fork(). |
| 10 | + * 2. scope.join() waits for all tasks to finish and throws FailedException if any task fails. |
| 11 | + * 3. Results are retrieved using subtask.get() after join(). |
| 12 | + * 4. Any running tasks are automatically cancelled if one fails. |
| 13 | + * |
| 14 | + * This makes concurrent code easier to read, safer, and less error-prone than manual thread management. |
| 15 | + */ |
| 16 | + |
| 17 | +void main() { |
| 18 | + // Open a structured task scope |
| 19 | + try (var scope = StructuredTaskScope.<String>open()) { |
| 20 | + |
| 21 | + // Fork tasks concurrently |
| 22 | + var task1 = scope.fork(() -> work("Task 1", 1000)); |
| 23 | + var task2 = scope.fork(() -> work("Task 2 (fails)", 500)); |
| 24 | + var task3 = scope.fork(() -> work("Task 3", 800)); |
| 25 | + |
| 26 | + // Wait for all tasks to complete; throws FailedException if any task failed |
| 27 | + scope.join(); |
| 28 | + |
| 29 | + // Retrieve results using get() after join() succeeds |
| 30 | + IO.println(task1.get()); |
| 31 | + IO.println(task2.get()); |
| 32 | + IO.println(task3.get()); |
| 33 | + |
| 34 | + } catch (StructuredTaskScope.FailedException e) { |
| 35 | + IO.println("One or more tasks failed: " + e.getCause()); |
| 36 | + } catch (InterruptedException e) { |
| 37 | + IO.println("Interrupted while waiting for tasks."); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +private static String work(String name, int delayMillis) throws Exception { |
| 42 | + Thread.sleep(delayMillis); |
| 43 | + if (name.contains("fails")) { |
| 44 | + throw new RuntimeException(name + " encountered an error!"); |
| 45 | + } |
| 46 | + return name + " completed successfully"; |
| 47 | +} |
0 commit comments