File: StructuredTaskScopeTest.java

package info (click to toggle)
openjdk-26 26~12ea-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 826,896 kB
  • sloc: java: 5,602,163; cpp: 1,336,664; xml: 1,321,153; ansic: 488,421; asm: 404,003; objc: 21,113; sh: 15,220; javascript: 13,281; python: 8,323; makefile: 2,519; perl: 357; awk: 351; pascal: 103; exp: 83; sed: 72; jsp: 24
file content (1767 lines) | stat: -rw-r--r-- 63,206 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
/*
 * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test id=platform
 * @bug 8284199 8296779 8306647
 * @summary Basic tests for StructuredTaskScope
 * @enablePreview
 * @run junit/othervm -DthreadFactory=platform StructuredTaskScopeTest
 */

/*
 * @test id=virtual
 * @enablePreview
 * @run junit/othervm -DthreadFactory=virtual StructuredTaskScopeTest
 */

import java.time.Duration;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.TimeoutException;
import java.util.concurrent.StructuredTaskScope.Configuration;
import java.util.concurrent.StructuredTaskScope.FailedException;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.StructureViolationException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.lang.Thread.State.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;

class StructuredTaskScopeTest {
    private static ScheduledExecutorService scheduler;
    private static List<ThreadFactory> threadFactories;

    @BeforeAll
    static void setup() throws Exception {
        scheduler = Executors.newSingleThreadScheduledExecutor();

        // thread factories
        String value = System.getProperty("threadFactory");
        List<ThreadFactory> list = new ArrayList<>();
        if (value == null || value.equals("platform"))
            list.add(Thread.ofPlatform().factory());
        if (value == null || value.equals("virtual"))
            list.add(Thread.ofVirtual().factory());
        assertTrue(list.size() > 0, "No thread factories for tests");
        threadFactories = list;
    }

    @AfterAll
    static void shutdown() {
        scheduler.shutdown();
    }

    private static Stream<ThreadFactory> factories() {
        return threadFactories.stream();
    }

    /**
     * Test that fork creates virtual threads when no ThreadFactory is configured.
     */
    @Test
    void testForkCreatesVirtualThread() throws Exception {
        Set<Thread> threads = ConcurrentHashMap.newKeySet();
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            for (int i = 0; i < 50; i++) {
                // runnable
                scope.fork(() -> {
                    threads.add(Thread.currentThread());
                });

                // callable
                scope.fork(() -> {
                    threads.add(Thread.currentThread());
                    return null;
                });
            }
            scope.join();
        }
        assertEquals(100, threads.size());
        threads.forEach(t -> assertTrue(t.isVirtual()));
    }

    /**
     * Test that fork create threads with the configured ThreadFactory.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkUsesThreadFactory(ThreadFactory factory) throws Exception {
        // TheadFactory that keeps reference to all threads it creates
        class RecordingThreadFactory implements ThreadFactory {
            final ThreadFactory delegate;
            final Set<Thread> threads = ConcurrentHashMap.newKeySet();
            RecordingThreadFactory(ThreadFactory delegate) {
                this.delegate = delegate;
            }
            @Override
            public Thread newThread(Runnable task) {
                Thread thread = delegate.newThread(task);
                threads.add(thread);
                return thread;
            }
            Set<Thread> threads() {
                return threads;
            }
        }
        var recordingThreadFactory = new RecordingThreadFactory(factory);
        Set<Thread> threads = ConcurrentHashMap.newKeySet();
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(recordingThreadFactory))) {

            for (int i = 0; i < 50; i++) {
                // runnable
                scope.fork(() -> {
                    threads.add(Thread.currentThread());
                });

                // callable
                scope.fork(() -> {
                    threads.add(Thread.currentThread());
                    return null;
                });
            }
            scope.join();
        }
        assertEquals(100, threads.size());
        assertEquals(recordingThreadFactory.threads(), threads);
    }

    /**
     * Test fork method is owner confined.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkConfined(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<Boolean>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            // random thread cannot fork
            try (var pool = Executors.newSingleThreadExecutor()) {
                Future<Void> future = pool.submit(() -> {
                    assertThrows(WrongThreadException.class, () -> {
                        scope.fork(() -> null);
                    });
                    return null;
                });
                future.get();
            }

            // subtask cannot fork
            Subtask<Boolean> subtask = scope.fork(() -> {
                assertThrows(WrongThreadException.class, () -> {
                    scope.fork(() -> null);
                });
                return true;
            });
            scope.join();
            assertTrue(subtask.get());
        }
    }

    /**
     * Test fork after join, no subtasks forked before join.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkAfterJoin1(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            scope.join();
            assertThrows(IllegalStateException.class, () -> scope.fork(() -> "bar"));
        }
    }

    /**
     * Test fork after join, subtasks forked before join.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkAfterJoin2(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.join();
            assertThrows(IllegalStateException.class, () -> scope.fork(() -> "bar"));
        }
    }

    /**
     * Test fork after join throws.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkAfterJoinThrows(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            var latch = new CountDownLatch(1);
            var subtask1 = scope.fork(() -> {
                latch.await();
                return "foo";
            });

            // join throws
            Thread.currentThread().interrupt();
            assertThrows(InterruptedException.class, scope::join);

            // fork should throw
            assertThrows(IllegalStateException.class, () -> scope.fork(() -> "bar"));
        }
    }

    /**
     * Test fork after task scope is cancelled. This test uses a custom Joiner to
     * cancel execution.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testForkAfterCancel2(ThreadFactory factory) throws Exception {
        var countingThreadFactory = new CountingThreadFactory(factory);
        var testJoiner = new CancelAfterOneJoiner<String>();

        try (var scope = StructuredTaskScope.open(testJoiner,
                cf -> cf.withThreadFactory(countingThreadFactory))) {

            // fork subtask, the scope should be cancelled when the subtask completes
            var subtask1 = scope.fork(() -> "foo");
            awaitCancelled(scope);

            assertEquals(1, countingThreadFactory.threadCount());
            assertEquals(1, testJoiner.onForkCount());
            assertEquals(1, testJoiner.onCompleteCount());

            // fork second subtask, it should not run
            var subtask2 = scope.fork(() -> "bar");

            // onFork should be invoked, newThread and onComplete should not be invoked
            assertEquals(1, countingThreadFactory.threadCount());
            assertEquals(2, testJoiner.onForkCount());
            assertEquals(1, testJoiner.onCompleteCount());

            scope.join();

            assertEquals(1, countingThreadFactory.threadCount());
            assertEquals(2, testJoiner.onForkCount());
            assertEquals(1, testJoiner.onCompleteCount());
            assertEquals("foo", subtask1.get());
            assertEquals(Subtask.State.UNAVAILABLE, subtask2.state());
        }
    }

    /**
     * Test fork after task scope is closed.
     */
    @Test
    void testForkAfterClose() {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            scope.close();
            assertThrows(IllegalStateException.class, () -> scope.fork(() -> null));
        }
    }

    /**
     * Test fork with a ThreadFactory that rejects creating a thread.
     */
    @Test
    void testForkRejectedExecutionException() {
        ThreadFactory factory = task -> null;
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            assertThrows(RejectedExecutionException.class, () -> scope.fork(() -> null));
        }
    }

    /**
     * Test join with no subtasks.
     */
    @Test
    void testJoinWithNoSubtasks() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            scope.join();
        }
    }

    /**
     * Test join with a remaining subtask.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinWithRemainingSubtasks(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            Subtask<String> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofMillis(100));
                return "foo";
            });
            scope.join();
            assertEquals("foo", subtask.get());
        }
    }

    /**
     * Test join after join completed with a result.
     */
    @Test
    void testJoinAfterJoin1() throws Exception {
        var results = new LinkedTransferQueue<>(List.of("foo", "bar", "baz"));
        Joiner<Object, String> joiner = results::take;
        try (var scope = StructuredTaskScope.open(joiner)) {
            scope.fork(() -> "foo");
            assertEquals("foo", scope.join());

            // join already called
            for (int i = 0 ; i < 3; i++) {
                assertThrows(IllegalStateException.class, scope::join);
            }
        }
    }

    /**
     * Test join after join completed with an exception.
     */
    @Test
    void testJoinAfterJoin2() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.anySuccessfulResultOrThrow())) {
            scope.fork(() -> { throw new FooException(); });
            Throwable ex = assertThrows(FailedException.class, scope::join);
            assertTrue(ex.getCause() instanceof FooException);

            // join already called
            for (int i = 0 ; i < 3; i++) {
                assertThrows(IllegalStateException.class, scope::join);
            }
        }
    }

    /**
     * Test join after join completed with a timeout.
     */
    @Test
    void testJoinAfterJoin3() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.anySuccessfulResultOrThrow(),
                cf -> cf.withTimeout(Duration.ofMillis(100)))) {
            // wait for scope to be cancelled by timeout
            awaitCancelled(scope);
            assertThrows(TimeoutException.class, scope::join);

            // join already called
            for (int i = 0 ; i < 3; i++) {
                assertThrows(IllegalStateException.class, scope::join);
            }
        }
    }

    /**
     * Test join method is owner confined.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinConfined(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<Boolean>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            // random thread cannot join
            try (var pool = Executors.newSingleThreadExecutor()) {
                Future<Void> future = pool.submit(() -> {
                    assertThrows(WrongThreadException.class, scope::join);
                    return null;
                });
                future.get();
            }

            // subtask cannot join
            Subtask<Boolean> subtask = scope.fork(() -> {
                assertThrows(WrongThreadException.class, () -> { scope.join(); });
                return true;
            });
            scope.join();
            assertTrue(subtask.get());
        }
    }

    /**
     * Test join with interrupt status set.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testInterruptJoin1(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            Subtask<String> subtask = scope.fork(() -> {
                Thread.sleep(60_000);
                return "foo";
            });

            // join should throw
            Thread.currentThread().interrupt();
            try {
                scope.join();
                fail("join did not throw");
            } catch (InterruptedException expected) {
                assertFalse(Thread.interrupted());   // interrupt status should be cleared
            }
        }
    }

    /**
     * Test interrupt of thread blocked in join.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testInterruptJoin2(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            var latch = new CountDownLatch(1);
            Subtask<String> subtask = scope.fork(() -> {
                Thread.sleep(60_000);
                return "foo";
            });

            // interrupt main thread when it blocks in join
            scheduleInterruptAt("java.util.concurrent.StructuredTaskScopeImpl.join");
            try {
                scope.join();
                fail("join did not throw");
            } catch (InterruptedException expected) {
                assertFalse(Thread.interrupted());   // interrupt status should be clear
            }
        }
    }

    /**
     * Test join when scope is cancelled.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinWhenCancelled(ThreadFactory factory) throws Exception {
        var countingThreadFactory = new CountingThreadFactory(factory);
        var testJoiner = new CancelAfterOneJoiner<String>();

        try (var scope = StructuredTaskScope.open(testJoiner,
                    cf -> cf.withThreadFactory(countingThreadFactory))) {

            // fork subtask, the scope should be cancelled when the subtask completes
            var subtask1 = scope.fork(() -> "foo");
            awaitCancelled(scope);

            // fork second subtask, it should not run
            var subtask2 = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return "bar";
            });

            scope.join();

            assertEquals("foo", subtask1.get());
            assertEquals(Subtask.State.UNAVAILABLE, subtask2.state());
        }
    }

    /**
     * Test join after scope is closed.
     */
    @Test
    void testJoinAfterClose() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            scope.close();
            assertThrows(IllegalStateException.class, () -> scope.join());
        }
    }

    /**
     * Test join with timeout, subtasks finish before timeout expires.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinWithTimeout1(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory)
                        .withTimeout(Duration.ofDays(1)))) {

            Subtask<String> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofSeconds(1));
                return "foo";
            });

            scope.join();

            assertFalse(scope.isCancelled());
            assertEquals("foo", subtask.get());
        }
    }

    /**
     * Test join with timeout, timeout expires before subtasks finish.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinWithTimeout2(ThreadFactory factory) throws Exception {
        long startMillis = millisTime();
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory)
                        .withTimeout(Duration.ofSeconds(2)))) {

            Subtask<Void> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return null;
            });

            assertThrows(TimeoutException.class, scope::join);
            expectDuration(startMillis, /*min*/1900, /*max*/20_000);

            assertTrue(scope.isCancelled());
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
        }
    }

    /**
     * Test join with timeout that has already expired.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testJoinWithTimeout3(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory)
                        .withTimeout(Duration.ofSeconds(-1)))) {

            Subtask<Void> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return null;
            });

            assertThrows(TimeoutException.class, scope::join);

            assertTrue(scope.isCancelled());
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
        }
    }

    /**
     * Test that cancelling execution interrupts unfinished threads. This test uses
     * a custom Joiner to cancel execution.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testCancelInterruptsThreads2(ThreadFactory factory) throws Exception {
        var testJoiner = new CancelAfterOneJoiner<String>();

        try (var scope = StructuredTaskScope.open(testJoiner,
                cf -> cf.withThreadFactory(factory))) {

            // fork subtask1 that runs for a long time
            var started = new CountDownLatch(1);
            var interrupted = new CountDownLatch(1);
            var subtask1 = scope.fork(() -> {
                started.countDown();
                try {
                    Thread.sleep(Duration.ofDays(1));
                } catch (InterruptedException e) {
                    interrupted.countDown();
                }
            });
            started.await();

            // fork subtask2, the scope should be cancelled when the subtask completes
            var subtask2 = scope.fork(() -> "bar");
            awaitCancelled(scope);

            // subtask1 should be interrupted
            interrupted.await();

            scope.join();
            assertEquals(Subtask.State.UNAVAILABLE, subtask1.state());
            assertEquals("bar", subtask2.get());
        }
    }

    /**
     * Test that timeout interrupts unfinished threads.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testTimeoutInterruptsThreads(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory)
                        .withTimeout(Duration.ofSeconds(2)))) {

            var started = new AtomicBoolean();
            var interrupted = new CountDownLatch(1);
            Subtask<Void> subtask = scope.fork(() -> {
                started.set(true);
                try {
                    Thread.sleep(Duration.ofDays(1));
                } catch (InterruptedException e) {
                    interrupted.countDown();
                }
                return null;
            });

            // wait for scope to be cancelled by timeout
            awaitCancelled(scope);

            // if subtask started then it should be interrupted
            if (started.get()) {
                interrupted.await();
            }

            assertThrows(TimeoutException.class, scope::join);

            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
        }
    }

    /**
     * Test close without join, no subtasks forked.
     */
    @Test
    void testCloseWithoutJoin1() {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            // do nothing
        }
    }

    /**
     * Test close without join, subtasks forked.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testCloseWithoutJoin2(ThreadFactory factory) {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            Subtask<String> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return null;
            });

            // first call to close should throw
            assertThrows(IllegalStateException.class, scope::close);

            // subsequent calls to close should not throw
            for (int i = 0; i < 3; i++) {
                scope.close();
            }

            // subtask result/exception not available
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);
        }
    }

    /**
     * Test close after join throws. Close should not throw as join attempted.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testCloseAfterJoinThrows(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            var subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return null;
            });

            // join throws
            Thread.currentThread().interrupt();
            assertThrows(InterruptedException.class, scope::join);
            assertThrows(IllegalStateException.class, subtask::get);

        }  // close should not throw
    }

    /**
     * Test close method is owner confined.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testCloseConfined(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<Boolean>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            // random thread cannot close scope
            try (var pool = Executors.newCachedThreadPool(factory)) {
                Future<Boolean> future = pool.submit(() -> {
                    assertThrows(WrongThreadException.class, scope::close);
                    return null;
                });
                future.get();
            }

            // subtask cannot close
            Subtask<Boolean> subtask = scope.fork(() -> {
                assertThrows(WrongThreadException.class, scope::close);
                return true;
            });
            scope.join();
            assertTrue(subtask.get());
        }
    }

    /**
     * Test close with interrupt status set.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testInterruptClose1(ThreadFactory factory) throws Exception {
        var testJoiner = new CancelAfterOneJoiner<String>();
        try (var scope = StructuredTaskScope.open(testJoiner,
                cf -> cf.withThreadFactory(factory))) {

            // fork first subtask, a straggler as it continues after being interrupted
            var started = new CountDownLatch(1);
            var done = new AtomicBoolean();
            scope.fork(() -> {
                started.countDown();
                try {
                    Thread.sleep(Duration.ofDays(1));
                } catch (InterruptedException e) {
                    // interrupted by cancel, expected
                }
                Thread.sleep(Duration.ofMillis(100)); // force close to wait
                done.set(true);
                return null;
            });
            started.await();

            // fork second subtask, the scope should be cancelled when this subtask completes
            scope.fork(() -> "bar");
            awaitCancelled(scope);

            scope.join();

            // invoke close with interrupt status set
            Thread.currentThread().interrupt();
            try {
                scope.close();
            } finally {
                assertTrue(Thread.interrupted());   // clear interrupt status
                assertTrue(done.get());
            }
        }
    }

    /**
     * Test interrupting thread waiting in close.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testInterruptClose2(ThreadFactory factory) throws Exception {
        var testJoiner = new CancelAfterOneJoiner<String>();
        try (var scope = StructuredTaskScope.open(testJoiner,
                cf -> cf.withThreadFactory(factory))) {

            Thread mainThread = Thread.currentThread();

            // fork first subtask, a straggler as it continues after being interrupted
            var started = new CountDownLatch(1);
            var done = new AtomicBoolean();
            scope.fork(() -> {
                started.countDown();
                try {
                    Thread.sleep(Duration.ofDays(1));
                } catch (InterruptedException e) {
                    // interrupted by cancel, expected
                }

                // interrupt main thread when it blocks in close
                interruptThreadAt(mainThread, "java.util.concurrent.StructuredTaskScopeImpl.close");

                Thread.sleep(Duration.ofMillis(100)); // force close to wait
                done.set(true);
                return null;
            });
            started.await();

            // fork second subtask, the scope should be cancelled when this subtask completes
            scope.fork(() -> "bar");
            awaitCancelled(scope);

            scope.join();

            // main thread will be interrupted while blocked in close
            try {
                scope.close();
            } finally {
                assertTrue(Thread.interrupted());   // clear interrupt status
                assertTrue(done.get());
            }
        }
    }

    /**
     * Test that closing an enclosing scope closes the thread flock of a nested scope.
     */
    @Test
    void testCloseThrowsStructureViolation() throws Exception {
        try (var scope1 = StructuredTaskScope.open(Joiner.awaitAll())) {
            try (var scope2 = StructuredTaskScope.open(Joiner.awaitAll())) {

                // close enclosing scope
                try {
                    scope1.close();
                    fail("close did not throw");
                } catch (StructureViolationException expected) { }

                // underlying flock should be closed
                var executed = new AtomicBoolean();
                Subtask<?> subtask = scope2.fork(() -> executed.set(true));
                assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
                scope2.join();
                assertFalse(executed.get());
                assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            }
        }
    }

    /**
     * Test that isCancelled returns true after close.
     */
    @Test
    void testIsCancelledAfterClose() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            assertFalse(scope.isCancelled());
            scope.close();
            assertTrue(scope.isCancelled());
        }
    }

    /**
     * Test Joiner.onFork throwing exception.
     */
    @Test
    void testOnForkThrows() throws Exception {
        var joiner = new Joiner<String, Void>() {
            @Override
            public boolean onFork(Subtask<? extends String> subtask) {
                throw new FooException();
            }
            @Override
            public Void result() {
                return null;
            }
        };
        try (var scope = StructuredTaskScope.open(joiner)) {
            assertThrows(FooException.class, () -> scope.fork(() -> "foo"));
        }
    }

    /**
     * Test Joiner.onFork returning true to cancel execution.
     */
    @Test
    void testOnForkCancelsExecution() throws Exception {
        var joiner = new Joiner<String, Void>() {
            @Override
            public boolean onFork(Subtask<? extends String> subtask) {
                return true;
            }
            @Override
            public Void result() {
                return null;
            }
        };
        try (var scope = StructuredTaskScope.open(joiner)) {
            assertFalse(scope.isCancelled());
            scope.fork(() -> "foo");
            assertTrue(scope.isCancelled());
            scope.join();
        }
    }

    /**
     * Test Joiner.onComplete throwing exception causes UHE to be invoked.
     */
    @Test
    void testOnCompleteThrows() throws Exception {
        var joiner = new Joiner<String, Void>() {
            @Override
            public boolean onComplete(Subtask<? extends String> subtask) {
                throw new FooException();
            }
            @Override
            public Void result() {
                return null;
            }
        };
        var excRef = new AtomicReference<Throwable>();
        Thread.UncaughtExceptionHandler uhe = (t, e) -> excRef.set(e);
        ThreadFactory factory = Thread.ofVirtual()
                .uncaughtExceptionHandler(uhe)
                .factory();
        try (var scope = StructuredTaskScope.open(joiner, cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.join();
            assertInstanceOf(FooException.class, excRef.get());
        }
    }

    /**
     * Test Joiner.onComplete returning true to cancel execution.
     */
    @Test
    void testOnCompleteCancelsExecution() throws Exception {
        var joiner = new Joiner<String, Void>() {
            @Override
            public boolean onComplete(Subtask<? extends String> subtask) {
                return true;
            }
            @Override
            public Void result() {
                return null;
            }
        };
        try (var scope = StructuredTaskScope.open(joiner)) {
            assertFalse(scope.isCancelled());
            scope.fork(() -> "foo");
            awaitCancelled(scope);
            scope.join();
        }
    }

    /**
     * Test toString.
     */
    @Test
    void testToString() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withName("duke"))) {

            // open
            assertTrue(scope.toString().contains("duke"));

            // closed
            scope.close();
            assertTrue(scope.toString().contains("duke"));
        }
    }

    /**
     * Test Subtask with task that completes successfully.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testSubtaskWhenSuccess(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            Subtask<String> subtask = scope.fork(() -> "foo");

            // before join
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);

            scope.join();

            // after join
            assertEquals(Subtask.State.SUCCESS, subtask.state());
            assertEquals("foo", subtask.get());
            assertThrows(IllegalStateException.class, subtask::exception);
        }
    }

    /**
     * Test Subtask with task that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testSubtaskWhenFailed(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {

            Subtask<String> subtask = scope.fork(() -> { throw new FooException(); });

            // before join
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);

            scope.join();

            // after join
            assertEquals(Subtask.State.FAILED, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertTrue(subtask.exception() instanceof FooException);
        }
    }

    /**
     * Test Subtask with a task that has not completed.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testSubtaskWhenNotCompleted(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            Subtask<Void> subtask = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return null;
            });

            // before join
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);

            // attempt join, join throws
            Thread.currentThread().interrupt();
            assertThrows(InterruptedException.class, scope::join);

            // after join
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);
        }
    }

    /**
     * Test Subtask forked after execution cancelled.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testSubtaskWhenCancelled(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(new CancelAfterOneJoiner<String>())) {
            scope.fork(() -> "foo");
            awaitCancelled(scope);

            var subtask = scope.fork(() -> "foo");

            // before join
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);

            scope.join();

            // after join
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalStateException.class, subtask::get);
            assertThrows(IllegalStateException.class, subtask::exception);
        }
    }

    /**
     * Test Subtask::toString.
     */
    @Test
    void testSubtaskToString() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            var latch = new CountDownLatch(1);
            var subtask1 = scope.fork(() -> {
                latch.await();
                return "foo";
            });
            var subtask2 = scope.fork(() -> { throw new FooException(); });

            // subtask1 result is unavailable
            assertTrue(subtask1.toString().contains("Unavailable"));
            latch.countDown();

            scope.join();

            assertTrue(subtask1.toString().contains("Completed successfully"));
            assertTrue(subtask2.toString().contains("Failed"));
        }
    }

    /**
     * Test Joiner.allSuccessfulOrThrow() with no subtasks.
     */
    @Test
    void testAllSuccessfulOrThrow1() throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.allSuccessfulOrThrow())) {
            var subtasks = scope.join().toList();
            assertTrue(subtasks.isEmpty());
        }
    }

    /**
     * Test Joiner.allSuccessfulOrThrow() with subtasks that complete successfully.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAllSuccessfulOrThrow2(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> "bar");
            var subtasks = scope.join().toList();
            assertEquals(List.of(subtask1, subtask2), subtasks);
            assertEquals("foo", subtask1.get());
            assertEquals("bar", subtask2.get());
        }
    }

    /**
     * Test Joiner.allSuccessfulOrThrow() with a subtask that complete successfully and
     * a subtask that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAllSuccessfulOrThrow3(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.fork(() -> { throw new FooException(); });
            try {
                scope.join();
            } catch (FailedException e) {
                assertTrue(e.getCause() instanceof FooException);
            }
        }
    }

    /**
     * Test Joiner.anySuccessfulResultOrThrow() with no subtasks.
     */
    @Test
    void testAnySuccessfulResultOrThrow1() throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.anySuccessfulResultOrThrow())) {
            try {
                scope.join();
            } catch (FailedException e) {
                assertTrue(e.getCause() instanceof NoSuchElementException);
            }
        }
    }

    /**
     * Test Joiner.anySuccessfulResultOrThrow() with a subtask that completes successfully.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAnySuccessfulResultOrThrow2(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            String result = scope.join();
            assertEquals("foo", result);
        }
    }

    /**
     * Test Joiner.anySuccessfulResultOrThrow() with a subtask that completes successfully
     * with a null result.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAnySuccessfulResultOrThrow3(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> null);
            String result = scope.join();
            assertNull(result);
        }
    }

    /**
     * Test Joiner.anySuccessfulResultOrThrow() with a subtask that complete succcessfully
     * and a subtask that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAnySuccessfulResultOrThrow4(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.fork(() -> { throw new FooException(); });
            String first = scope.join();
            assertEquals("foo", first);
        }
    }

    /**
     * Test Joiner.anySuccessfulResultOrThrow() with a subtask that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAnySuccessfulResultOrThrow5(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.anySuccessfulResultOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> { throw new FooException(); });
            Throwable ex = assertThrows(FailedException.class, scope::join);
            assertTrue(ex.getCause() instanceof FooException);
        }
    }

    /**
     * Test Joiner.awaitAllSuccessfulOrThrow() with no subtasks.
     */
    @Test
    void testAwaitSuccessfulOrThrow1() throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAllSuccessfulOrThrow())) {
            var result = scope.join();
            assertNull(result);
        }
    }

    /**
     * Test Joiner.awaitAllSuccessfulOrThrow() with subtasks that complete successfully.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAwaitSuccessfulOrThrow2(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAllSuccessfulOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> "bar");
            var result = scope.join();
            assertNull(result);
            assertEquals("foo", subtask1.get());
            assertEquals("bar", subtask2.get());
        }
    }

    /**
     * Test Joiner.awaitAllSuccessfulOrThrow() with a subtask that complete successfully and
     * a subtask that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAwaitSuccessfulOrThrow3(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAllSuccessfulOrThrow(),
                cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.fork(() -> { throw new FooException(); });
            try {
                scope.join();
            } catch (FailedException e) {
                assertTrue(e.getCause() instanceof FooException);
            }
        }
    }

    /**
     * Test Joiner.awaitAll() with no subtasks.
     */
    @Test
    void testAwaitAll1() throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            var result = scope.join();
            assertNull(result);
        }
    }

    /**
     * Test Joiner.awaitAll() with subtasks that complete successfully.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAwaitAll2(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> "bar");
            var result = scope.join();
            assertNull(result);
            assertEquals("foo", subtask1.get());
            assertEquals("bar", subtask2.get());
        }
    }

    /**
     * Test Joiner.awaitAll() with a subtask that complete successfully and a subtask
     * that fails.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAwaitAll3(ThreadFactory factory) throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll(),
                cf -> cf.withThreadFactory(factory))) {
            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> { throw new FooException(); });
            var result = scope.join();
            assertNull(result);
            assertEquals("foo", subtask1.get());
            assertTrue(subtask2.exception() instanceof FooException);
        }
    }

    /**
     * Test Joiner.allUntil(Predicate) with no subtasks.
     */
    @Test
    void testAllUntil1() throws Throwable {
        try (var scope = StructuredTaskScope.open(Joiner.allUntil(s -> false))) {
            var subtasks = scope.join();
            assertEquals(0, subtasks.count());
        }
    }

    /**
     * Test Joiner.allUntil(Predicate) with no cancellation.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAllUntil2(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(s -> false),
                cf -> cf.withThreadFactory(factory))) {

            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> { throw new FooException(); });

            var subtasks = scope.join().toList();
            assertEquals(2, subtasks.size());

            assertSame(subtask1, subtasks.get(0));
            assertSame(subtask2, subtasks.get(1));
            assertEquals("foo", subtask1.get());
            assertTrue(subtask2.exception() instanceof FooException);
        }
    }

    /**
     * Test Joiner.allUntil(Predicate) with cancellation after one subtask completes.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAllUntil3(ThreadFactory factory) throws Exception {
        try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(s -> true),
                cf -> cf.withThreadFactory(factory))) {

            var subtask1 = scope.fork(() -> "foo");
            var subtask2 = scope.fork(() -> {
                Thread.sleep(Duration.ofDays(1));
                return "bar";
            });

            var subtasks = scope.join().toList();

            assertEquals(2, subtasks.size());
            assertSame(subtask1, subtasks.get(0));
            assertSame(subtask2, subtasks.get(1));
            assertEquals("foo", subtask1.get());
            assertEquals(Subtask.State.UNAVAILABLE, subtask2.state());
        }
    }

    /**
     * Test Joiner.allUntil(Predicate) with cancellation after serveral subtasks complete.
     */
    @ParameterizedTest
    @MethodSource("factories")
    void testAllUntil4(ThreadFactory factory) throws Exception {

        // cancel execution after two or more failures
        class CancelAfterTwoFailures<T> implements Predicate<Subtask<? extends T>> {
            final AtomicInteger failedCount = new AtomicInteger();
            @Override
            public boolean test(Subtask<? extends T> subtask) {
                return subtask.state() == Subtask.State.FAILED
                        && failedCount.incrementAndGet() >= 2;
            }
        }
        var joiner = Joiner.allUntil(new CancelAfterTwoFailures<String>());

        try (var scope = StructuredTaskScope.open(joiner)) {
            int forkCount = 0;

            // fork subtasks until execution cancelled
            while (!scope.isCancelled()) {
                scope.fork(() -> "foo");
                scope.fork(() -> { throw new FooException(); });
                forkCount += 2;
                Thread.sleep(Duration.ofMillis(20));
            }

            var subtasks = scope.join().toList();
            assertEquals(forkCount, subtasks.size());

            long failedCount = subtasks.stream()
                    .filter(s -> s.state() == Subtask.State.FAILED)
                    .count();
            assertTrue(failedCount >= 2);
        }
    }

    /**
     * Test Test Joiner.allUntil(Predicate) where the Predicate's test method throws.
     */
    @Test
    void testAllUntil5() throws Exception {
        var joiner = Joiner.allUntil(_ -> { throw new FooException(); });
        var excRef = new AtomicReference<Throwable>();
        Thread.UncaughtExceptionHandler uhe = (t, e) -> excRef.set(e);
        ThreadFactory factory = Thread.ofVirtual()
                .uncaughtExceptionHandler(uhe)
                .factory();
        try (var scope = StructuredTaskScope.open(joiner, cf -> cf.withThreadFactory(factory))) {
            scope.fork(() -> "foo");
            scope.join();
            assertInstanceOf(FooException.class, excRef.get());
        }
    }

    /**
     * Test Joiner default methods.
     */
    @Test
    void testJoinerDefaultMethods() throws Exception {
        try (var scope = StructuredTaskScope.open(new CancelAfterOneJoiner<String>())) {

            // need subtasks to test default methods
            var subtask1 = scope.fork(() -> "foo");
            awaitCancelled(scope);
            var subtask2 = scope.fork(() -> "bar");
            scope.join();

            assertEquals(Subtask.State.SUCCESS, subtask1.state());
            assertEquals(Subtask.State.UNAVAILABLE, subtask2.state());

            // Joiner that does not override default methods
            Joiner<Object, Void> joiner = () -> null;
            assertThrows(NullPointerException.class, () -> joiner.onFork(null));
            assertThrows(NullPointerException.class, () -> joiner.onComplete(null));
            assertThrows(IllegalArgumentException.class, () -> joiner.onFork(subtask1));
            assertFalse(joiner.onFork(subtask2));
            assertFalse(joiner.onComplete(subtask1));
            assertThrows(IllegalArgumentException.class, () -> joiner.onComplete(subtask2));
        }
    }

    /**
     * Test Joiners onFork/onComplete methods with a subtask in an unexpected state.
     */
    @Test
    void testJoinersWithUnavailableResult() throws Exception {
        try (var scope = StructuredTaskScope.open()) {
            var done = new CountDownLatch(1);
            var subtask = scope.fork(() -> {
                done.await();
                return null;
            });

            // onComplete with uncompleted task should throw IAE
            assertEquals(Subtask.State.UNAVAILABLE, subtask.state());
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.allSuccessfulOrThrow().onComplete(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.anySuccessfulResultOrThrow().onComplete(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.awaitAllSuccessfulOrThrow().onComplete(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.awaitAll().onComplete(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.allUntil(_ -> false).onComplete(subtask));

            done.countDown();
            scope.join();

            // onFork with completed task should throw IAE
            assertEquals(Subtask.State.SUCCESS, subtask.state());
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.allSuccessfulOrThrow().onFork(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.anySuccessfulResultOrThrow().onFork(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.awaitAllSuccessfulOrThrow().onFork(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.awaitAll().onFork(subtask));
            assertThrows(IllegalArgumentException.class,
                    () -> Joiner.allUntil(_ -> false).onFork(subtask));
        }

    }

    /**
     * Test the Configuration function apply method throwing an exception.
     */
    @Test
    void testConfigFunctionThrows() throws Exception {
        assertThrows(FooException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(),
                                               cf -> { throw new FooException(); }));
    }

    /**
     * Test Configuration equals/hashCode/toString
     */
    @Test
    void testConfigMethods() throws Exception {
        Function<Configuration, Configuration> testConfig = cf -> {
            var name = "duke";
            var threadFactory = Thread.ofPlatform().factory();
            var timeout = Duration.ofSeconds(10);

            assertEquals(cf, cf);
            assertEquals(cf.withName(name), cf.withName(name));
            assertEquals(cf.withThreadFactory(threadFactory), cf.withThreadFactory(threadFactory));
            assertEquals(cf.withTimeout(timeout), cf.withTimeout(timeout));

            assertNotEquals(cf, cf.withName(name));
            assertNotEquals(cf, cf.withThreadFactory(threadFactory));
            assertNotEquals(cf, cf.withTimeout(timeout));

            assertEquals(cf.withName(name).hashCode(), cf.withName(name).hashCode());
            assertEquals(cf.withThreadFactory(threadFactory).hashCode(),
                    cf.withThreadFactory(threadFactory).hashCode());
            assertEquals(cf.withTimeout(timeout).hashCode(), cf.withTimeout(timeout).hashCode());

            assertTrue(cf.withName(name).toString().contains(name));
            assertTrue(cf.withThreadFactory(threadFactory).toString().contains(threadFactory.toString()));
            assertTrue(cf.withTimeout(timeout).toString().contains(timeout.toString()));

            return cf;
        };
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll(), testConfig)) {
            // do nothing
        }
    }

    /**
     * Test for NullPointerException.
     */
    @Test
    void testNulls() throws Exception {
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(null));
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(null, cf -> cf));
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(), null));

        assertThrows(NullPointerException.class, () -> Joiner.allUntil(null));

        // fork
        try (var scope = StructuredTaskScope.open(Joiner.awaitAll())) {
            assertThrows(NullPointerException.class, () -> scope.fork((Callable<Object>) null));
            assertThrows(NullPointerException.class, () -> scope.fork((Runnable) null));
        }

        // Configuration and withXXX methods
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(), cf -> null));
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(), cf -> cf.withName(null)));
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(), cf -> cf.withThreadFactory(null)));
        assertThrows(NullPointerException.class,
                () -> StructuredTaskScope.open(Joiner.awaitAll(), cf -> cf.withTimeout(null)));

        // Joiner.onFork/onComplete
        assertThrows(NullPointerException.class,
                () -> Joiner.awaitAllSuccessfulOrThrow().onFork(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.awaitAllSuccessfulOrThrow().onComplete(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.awaitAll().onFork(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.awaitAll().onComplete(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.allSuccessfulOrThrow().onFork(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.allSuccessfulOrThrow().onComplete(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.anySuccessfulResultOrThrow().onFork(null));
        assertThrows(NullPointerException.class,
                () -> Joiner.anySuccessfulResultOrThrow().onComplete(null));
    }

    /**
     * ThreadFactory that counts usage.
     */
    private static class CountingThreadFactory implements ThreadFactory {
        final ThreadFactory delegate;
        final AtomicInteger threadCount = new AtomicInteger();
        CountingThreadFactory(ThreadFactory delegate) {
            this.delegate = delegate;
        }
        @Override
        public Thread newThread(Runnable task) {
            threadCount.incrementAndGet();
            return delegate.newThread(task);
        }
        int threadCount() {
            return threadCount.get();
        }
    }

    /**
     * A joiner that counts that counts the number of subtasks that are forked and the
     * number of subtasks that complete.
     */
    private static class CountingJoiner<T> implements Joiner<T, Void> {
        final AtomicInteger onForkCount = new AtomicInteger();
        final AtomicInteger onCompleteCount = new AtomicInteger();
        @Override
        public boolean onFork(Subtask<? extends T> subtask) {
            onForkCount.incrementAndGet();
            return false;
        }
        @Override
        public boolean onComplete(Subtask<? extends T> subtask) {
            onCompleteCount.incrementAndGet();
            return false;
        }
        @Override
        public Void result() {
            return null;
        }
        int onForkCount() {
            return onForkCount.get();
        }
        int onCompleteCount() {
            return onCompleteCount.get();
        }
    }

    /**
     * A joiner that cancels execution when a subtask completes. It also keeps a count
     * of the number of subtasks that are forked and the number of subtasks that complete.
     */
    private static class CancelAfterOneJoiner<T> implements Joiner<T, Void> {
        final AtomicInteger onForkCount = new AtomicInteger();
        final AtomicInteger onCompleteCount = new AtomicInteger();
        @Override
        public boolean onFork(Subtask<? extends T> subtask) {
            onForkCount.incrementAndGet();
            return false;
        }
        @Override
        public boolean onComplete(Subtask<? extends T> subtask) {
            onCompleteCount.incrementAndGet();
            return true;
        }
        @Override
        public Void result() {
            return null;
        }
        int onForkCount() {
            return onForkCount.get();
        }
        int onCompleteCount() {
            return onCompleteCount.get();
        }
    }

    /**
     * A runtime exception for tests.
     */
    private static class FooException extends RuntimeException {
        FooException() { }
        FooException(Throwable cause) { super(cause); }
    }

    /**
     * Returns the current time in milliseconds.
     */
    private long millisTime() {
        long now = System.nanoTime();
        return TimeUnit.MILLISECONDS.convert(now, TimeUnit.NANOSECONDS);
    }

    /**
     * Check the duration of a task
     * @param start start time, in milliseconds
     * @param min minimum expected duration, in milliseconds
     * @param max maximum expected duration, in milliseconds
     * @return the duration (now - start), in milliseconds
     */
    private long expectDuration(long start, long min, long max) {
        long duration = millisTime() - start;
        assertTrue(duration >= min,
                "Duration " + duration + "ms, expected >= " + min + "ms");
        assertTrue(duration <= max,
                "Duration " + duration + "ms, expected <= " + max + "ms");
        return duration;
    }

    /**
     * Wait for the given scope to be cancelled.
     */
    private static void awaitCancelled(StructuredTaskScope<?, ?> scope) throws InterruptedException {
        while (!scope.isCancelled()) {
            Thread.sleep(Duration.ofMillis(20));
        }
    }

    /**
     * Interrupts a thread when it waits (timed or untimed) at location "{@code c.m}".
     * {@code c} is the fully qualified class name and {@code m} is the method name.
     */
    private void interruptThreadAt(Thread target, String location) throws InterruptedException {
        int index = location.lastIndexOf('.');
        String className = location.substring(0, index);
        String methodName = location.substring(index + 1);

        boolean found = false;
        while (!found) {
            Thread.State state = target.getState();
            assertTrue(state != TERMINATED);
            if ((state == WAITING || state == TIMED_WAITING)
                    && contains(target.getStackTrace(), className, methodName)) {
                found = true;
            } else {
                Thread.sleep(20);
            }
        }
        target.interrupt();
    }

    /**
     * Schedules the current thread to be interrupted when it waits (timed or untimed)
     * at the given location.
     */
    private void scheduleInterruptAt(String location) {
        Thread target = Thread.currentThread();
        scheduler.submit(() -> {
            interruptThreadAt(target, location);
            return null;
        });
    }

    /**
     * Returns true if the given stack trace contains an element for the given class
     * and method name.
     */
    private boolean contains(StackTraceElement[] stack, String className, String methodName) {
        return Arrays.stream(stack)
                .anyMatch(e -> className.equals(e.getClassName())
                        && methodName.equals(e.getMethodName()));
    }
}