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 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
|
/*
* Copyright (c) 2019, 2024, 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=default
* @bug 8284161 8286788 8321270
* @summary Test Thread API with virtual threads
* @modules java.base/java.lang:+open jdk.management
* @library /test/lib
* @build LockingMode
* @run junit/othervm --enable-native-access=ALL-UNNAMED ThreadAPI
*/
/*
* @test id=no-vmcontinuations
* @requires vm.continuations
* @modules java.base/java.lang:+open jdk.management
* @library /test/lib
* @build LockingMode
* @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations
* --enable-native-access=ALL-UNNAMED ThreadAPI
*/
import java.time.Duration;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;
import java.nio.channels.Selector;
import jdk.test.lib.thread.VThreadPinner;
import jdk.test.lib.thread.VThreadRunner; // ensureParallelism requires jdk.management
import jdk.test.lib.thread.VThreadScheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.condition.DisabledIf;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
class ThreadAPI {
private static final Object lock = new Object();
// used for scheduling thread interrupt
private static ScheduledExecutorService scheduler;
@BeforeAll
static void setup() {
ThreadFactory factory = Executors.defaultThreadFactory();
scheduler = Executors.newSingleThreadScheduledExecutor(factory);
// need >=2 carriers for testing pinning
VThreadRunner.ensureParallelism(2);
}
@AfterAll
static void finish() {
scheduler.shutdown();
}
/**
* An operation that does not return a result but may throw an exception.
*/
@FunctionalInterface
interface ThrowingRunnable {
void run() throws Exception;
}
/**
* Test Thread.currentThread before/after park.
*/
@Test
void testCurrentThread1() throws Exception {
var before = new AtomicReference<Thread>();
var after = new AtomicReference<Thread>();
var thread = Thread.ofVirtual().start(() -> {
before.set(Thread.currentThread());
LockSupport.park();
after.set(Thread.currentThread());
});
await(thread, Thread.State.WAITING);
LockSupport.unpark(thread);
thread.join();
assertTrue(before.get() == thread);
assertTrue(after.get() == thread);
}
/**
* Test Thread.currentThread before/after entering synchronized block.
*/
@Test
void testCurrentThread2() throws Exception {
var ref1 = new AtomicReference<Thread>();
var ref2 = new AtomicReference<Thread>();
var ref3 = new AtomicReference<Thread>();
var thread = Thread.ofVirtual().unstarted(() -> {
ref1.set(Thread.currentThread());
synchronized (lock) {
ref2.set(Thread.currentThread());
}
ref3.set(Thread.currentThread());
});
synchronized (lock) {
thread.start();
await(thread, Thread.State.BLOCKED);
}
thread.join();
assertTrue(ref1.get() == thread);
assertTrue(ref2.get() == thread);
assertTrue(ref3.get() == thread);
}
/**
* Test Thread.currentThread before/after acquiring lock.
*/
@Test
void testCurrentThread3() throws Exception {
var ref1 = new AtomicReference<Thread>();
var ref2 = new AtomicReference<Thread>();
var ref3 = new AtomicReference<Thread>();
var lock = new ReentrantLock();
var thread = Thread.ofVirtual().unstarted(() -> {
ref1.set(Thread.currentThread());
lock.lock();
try {
ref2.set(Thread.currentThread());
} finally {
lock.unlock();
}
ref3.set(Thread.currentThread());
});
lock.lock();
try {
thread.start();
await(thread, Thread.State.WAITING);
} finally {
lock.unlock();
}
thread.join();
assertTrue(ref1.get() == thread);
assertTrue(ref2.get() == thread);
assertTrue(ref3.get() == thread);
}
/**
* Test Thread::run.
*/
@Test
void testRun1() throws Exception {
var ref = new AtomicBoolean();
var thread = Thread.ofVirtual().unstarted(() -> ref.set(true));
thread.run();
assertFalse(ref.get());
}
/**
* Test Thread::start.
*/
@Test
void testStart1() throws Exception {
var ref = new AtomicBoolean();
var thread = Thread.ofVirtual().unstarted(() -> ref.set(true));
assertFalse(ref.get());
thread.start();
thread.join();
assertTrue(ref.get());
}
/**
* Test Thread::start, thread already started.
*/
@Test
void testStart2() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
try {
assertThrows(IllegalThreadStateException.class, thread::start);
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::start, thread already terminated.
*/
@Test
void testStart3() throws Exception {
var thread = Thread.ofVirtual().start(() -> { });
thread.join();
assertThrows(IllegalThreadStateException.class, thread::start);
}
/**
* Test Thread.startVirtualThread.
*/
@Test
void testStartVirtualThread() throws Exception {
var ref = new AtomicReference<Thread>();
Thread vthread = Thread.startVirtualThread(() -> {
ref.set(Thread.currentThread());
LockSupport.park();
});
try {
assertTrue(vthread.isVirtual());
// Thread.currentThread() returned by the virtual thread
Thread current;
while ((current = ref.get()) == null) {
Thread.sleep(10);
}
assertTrue(current == vthread);
} finally {
LockSupport.unpark(vthread);
}
assertThrows(NullPointerException.class, () -> Thread.startVirtualThread(null));
}
/**
* Test Thread::stop from current thread.
*/
@Test
void testStop1() throws Exception {
VThreadRunner.run(() -> {
Thread t = Thread.currentThread();
assertThrows(UnsupportedOperationException.class, t::stop);
});
}
/**
* Test Thread::stop from another thread.
*/
@Test
void testStop2() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
try {
Thread.sleep(20*1000);
} catch (InterruptedException e) { }
});
try {
assertThrows(UnsupportedOperationException.class, thread::stop);
} finally {
thread.interrupt();
thread.join();
}
}
/**
* Test Thread.join before thread starts, platform thread invokes join.
*/
@Test
void testJoin1() throws Exception {
var thread = Thread.ofVirtual().unstarted(() -> { });
thread.join();
thread.join(0);
thread.join(0, 0);
thread.join(100);
thread.join(100, 0);
assertThrows(IllegalThreadStateException.class,
() -> thread.join(Duration.ofMillis(-100)));
assertThrows(IllegalThreadStateException.class,
() -> thread.join(Duration.ofMillis(0)));
assertThrows(IllegalThreadStateException.class,
() -> thread.join(Duration.ofMillis(100)));
}
/**
* Test Thread.join before thread starts, virtual thread invokes join.
*/
@Test
void testJoin2() throws Exception {
VThreadRunner.run(this::testJoin1);
}
/**
* Test Thread.join where thread does not terminate, platform thread invokes join.
*/
@Test
void testJoin3() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
try {
thread.join(20);
thread.join(20, 0);
thread.join(20, 20);
thread.join(0, 20);
assertFalse(thread.join(Duration.ofMillis(-20)));
assertFalse(thread.join(Duration.ofMillis(0)));
assertFalse(thread.join(Duration.ofMillis(20)));
assertTrue(thread.isAlive());
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread.join where thread does not terminate, virtual thread invokes join.
*/
@Test
void testJoin4() throws Exception {
VThreadRunner.run(this::testJoin3);
}
/**
* Test Thread.join where thread terminates, platform thread invokes join.
*/
@Test
void testJoin5() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
});
thread.join();
assertFalse(thread.isAlive());
}
/**
* Test Thread.join where thread terminates, virtual thread invokes join.
*/
@Test
void testJoin6() throws Exception {
VThreadRunner.run(this::testJoin5);
}
/**
* Test Thread.join where thread terminates, platform thread invokes timed-join.
*/
@Test
void testJoin7() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
});
thread.join(10*1000);
assertFalse(thread.isAlive());
}
/**
* Test Thread.join where thread terminates, virtual thread invokes timed-join.
*/
@Test
void testJoin8() throws Exception {
VThreadRunner.run(this::testJoin7);
}
/**
* Test Thread.join where thread terminates, platform thread invokes timed-join.
*/
@Test
void testJoin11() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
});
assertTrue(thread.join(Duration.ofSeconds(10)));
assertFalse(thread.isAlive());
}
/**
* Test Thread.join where thread terminates, virtual thread invokes timed-join.
*/
@Test
void testJoin12() throws Exception {
VThreadRunner.run(this::testJoin11);
}
/**
* Test Thread.join where thread already terminated, platform thread invokes join.
*/
@Test
void testJoin13() throws Exception {
var thread = Thread.ofVirtual().start(() -> { });
while (thread.isAlive()) {
Thread.sleep(10);
}
thread.join();
thread.join(0);
thread.join(0, 0);
thread.join(100);
thread.join(100, 0);
assertTrue(thread.join(Duration.ofMillis(-100)));
assertTrue(thread.join(Duration.ofMillis(0)));
assertTrue(thread.join(Duration.ofMillis(100)));
}
/**
* Test Thread.join where thread already terminated, virtual thread invokes join.
*/
@Test
void testJoin14() throws Exception {
VThreadRunner.run(this::testJoin13);
}
/**
* Test platform thread invoking Thread.join with interrupt status set.
*/
@Test
void testJoin15() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
Thread.currentThread().interrupt();
try {
assertThrows(InterruptedException.class, thread::join);
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test virtual thread invoking Thread.join with interrupt status set.
*/
@Test
void testJoin16() throws Exception {
VThreadRunner.run(this::testJoin15);
}
/**
* Test platform thread invoking timed-Thread.join with interrupt status set.
*/
@Test
void testJoin17() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
Thread.currentThread().interrupt();
try {
assertThrows(InterruptedException.class, () -> thread.join(100));
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test virtual thread invoking timed-Thread.join with interrupt status set.
*/
@Test
void testJoin18() throws Exception {
VThreadRunner.run(this::testJoin17);
}
/**
* Test platform thread invoking timed-Thread.join with interrupt status set.
*/
@Test
void testJoin19() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
Thread.currentThread().interrupt();
try {
assertThrows(InterruptedException.class,
() -> thread.join(Duration.ofMillis(100)));
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test virtual thread invoking timed-Thread.join with interrupt status set.
*/
@Test
void testJoin20() throws Exception {
VThreadRunner.run(this::testJoin19);
}
/**
* Test interrupt of platform thread blocked in Thread.join.
*/
@Test
void testJoin21() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
scheduleInterrupt(Thread.currentThread(), 100);
try {
assertThrows(InterruptedException.class, thread::join);
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test interrupt of virtual thread blocked in Thread.join.
*/
@Test
void testJoin22() throws Exception {
VThreadRunner.run(this::testJoin17);
}
/**
* Test interrupt of platform thread blocked in timed-Thread.join.
*/
@Test
void testJoin23() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
scheduleInterrupt(Thread.currentThread(), 100);
try {
assertThrows(InterruptedException.class, () -> thread.join(10*1000));
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test interrupt of virtual thread blocked in Thread.join.
*/
@Test
void testJoin24() throws Exception {
VThreadRunner.run(this::testJoin23);
}
/**
* Test interrupt of platform thread blocked in Thread.join.
*/
@Test
void testJoin25() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
scheduleInterrupt(Thread.currentThread(), 100);
try {
assertThrows(InterruptedException.class,
() -> thread.join(Duration.ofSeconds(10)));
} finally {
Thread.interrupted();
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test interrupt of virtual thread blocked in Thread.join.
*/
@Test
void testJoin26() throws Exception {
VThreadRunner.run(this::testJoin25);
}
/**
* Test virtual thread calling Thread.join to wait for platform thread to terminate.
*/
@Test
void testJoin27() throws Exception {
AtomicBoolean done = new AtomicBoolean();
VThreadRunner.run(() -> {
var thread = new Thread(() -> {
while (!done.get()) {
LockSupport.park();
}
});
thread.start();
try {
assertFalse(thread.join(Duration.ofMillis(-100)));
assertFalse(thread.join(Duration.ofMillis(0)));
assertFalse(thread.join(Duration.ofMillis(100)));
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
});
}
/**
* Test virtual thread calling Thread.join to wait for platform thread to terminate.
*/
@Test
void testJoin28() throws Exception {
long nanos = TimeUnit.NANOSECONDS.convert(100, TimeUnit.MILLISECONDS);
VThreadRunner.run(() -> {
var thread = new Thread(() -> LockSupport.parkNanos(nanos));
thread.start();
try {
assertTrue(thread.join(Duration.ofSeconds(Integer.MAX_VALUE)));
assertFalse(thread.isAlive());
} finally {
LockSupport.unpark(thread);
thread.join();
}
});
}
/**
* Test virtual thread with interrupt status set calling Thread.join to wait
* for platform thread to terminate.
*/
@Test
void testJoin29() throws Exception {
VThreadRunner.run(() -> {
var thread = new Thread(LockSupport::park);
thread.start();
Thread.currentThread().interrupt();
try {
thread.join(Duration.ofSeconds(Integer.MAX_VALUE));
fail("join not interrupted");
} catch (InterruptedException expected) {
assertFalse(Thread.interrupted());
} finally {
LockSupport.unpark(thread);
thread.join();
}
});
}
/**
* Test interrupting virtual thread that is waiting in Thread.join for
* platform thread to terminate.
*/
@Test
void testJoin30() throws Exception {
VThreadRunner.run(() -> {
AtomicBoolean done = new AtomicBoolean();
var thread = new Thread(() -> {
while (!done.get()) {
LockSupport.park();
}
});
thread.start();
scheduleInterrupt(Thread.currentThread(), 100);
try {
thread.join(Duration.ofSeconds(Integer.MAX_VALUE));
fail("join not interrupted");
} catch (InterruptedException expected) {
assertFalse(Thread.interrupted());
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
});
}
/**
* Test platform thread invoking Thread.join on a thread that is parking
* and unparking.
*/
@Test
void testJoin31() throws Exception {
Thread thread = Thread.ofVirtual().start(() -> {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
LockSupport.parkNanos(Duration.ofMillis(20).toNanos());
}
}
});
thread.join();
assertFalse(thread.isAlive());
}
/**
* Test virtual thread invoking Thread.join on a thread that is parking
* and unparking.
*/
@Test
void testJoin32() throws Exception {
VThreadRunner.run(this::testJoin31);
}
/**
* Test platform thread invoking timed-Thread.join on a thread that is parking
* and unparking while pinned.
*/
@Test
void testJoin33() throws Exception {
AtomicBoolean done = new AtomicBoolean();
Thread thread = Thread.ofVirtual().start(() -> {
VThreadPinner.runPinned(() -> {
while (!done.get()) {
LockSupport.parkNanos(Duration.ofMillis(20).toNanos());
}
});
});
try {
assertFalse(thread.join(Duration.ofMillis(100)));
} finally {
done.set(true);
thread.join();
}
}
/**
* Test virtual thread invoking timed-Thread.join on a thread that is parking
* and unparking while pinned.
*/
@Test
void testJoin34() throws Exception {
VThreadRunner.run(this::testJoin33);
}
/**
* Test Thread.join(null).
*/
@Test
void testJoin35() throws Exception {
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
// unstarted
assertThrows(NullPointerException.class, () -> thread.join(null));
// started
thread.start();
try {
assertThrows(NullPointerException.class, () -> thread.join(null));
} finally {
LockSupport.unpark(thread);
}
thread.join();
// terminated
assertThrows(NullPointerException.class, () -> thread.join(null));
}
/**
* Test Thread.interrupt on current thread.
*/
@Test
void testInterrupt1() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
assertFalse(me.isInterrupted());
me.interrupt();
assertTrue(me.isInterrupted());
Thread.interrupted(); // clear interrupt status
assertFalse(me.isInterrupted());
me.interrupt();
});
}
/**
* Test Thread.interrupt before thread started.
*/
@Test
void testInterrupt2() throws Exception {
var thread = Thread.ofVirtual().unstarted(() -> { });
thread.interrupt();
assertTrue(thread.isInterrupted());
}
/**
* Test Thread.interrupt after thread started.
*/
@Test
void testInterrupt3() throws Exception {
var thread = Thread.ofVirtual().start(() -> { });
thread.join();
thread.interrupt();
assertTrue(thread.isInterrupted());
}
/**
* Test termination with interrupt status set.
*/
@Test
void testInterrupt4() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
Thread.currentThread().interrupt();
});
thread.join();
assertTrue(thread.isInterrupted());
}
/**
* Test Thread.interrupt of thread blocked in Selector.select.
*/
@Test
void testInterrupt5() throws Exception {
var exception = new AtomicReference<Exception>();
var thread = Thread.ofVirtual().start(() -> {
try {
try (var sel = Selector.open()) {
sel.select();
assertTrue(Thread.currentThread().isInterrupted());
}
} catch (Exception e) {
exception.set(e);
}
});
Thread.sleep(100); // give time for thread to block
thread.interrupt();
thread.join();
assertNull(exception.get());
}
/**
* Test Thread.interrupt of thread parked in sleep.
*/
@Test
void testInterrupt6() throws Exception {
var exception = new AtomicReference<Exception>();
var thread = Thread.ofVirtual().start(() -> {
try {
try {
Thread.sleep(60*1000);
fail("sleep not interrupted");
} catch (InterruptedException e) {
// interrupt status should be reset
assertFalse(Thread.interrupted());
}
} catch (Exception e) {
exception.set(e);
}
});
await(thread, Thread.State.TIMED_WAITING);
thread.interrupt();
thread.join();
assertNull(exception.get());
}
/**
* Test Thread.interrupt of parked thread.
*/
@Test
void testInterrupt7() throws Exception {
var exception = new AtomicReference<Exception>();
var thread = Thread.ofVirtual().start(() -> {
try {
LockSupport.park();
assertTrue(Thread.currentThread().isInterrupted());
} catch (Exception e) {
exception.set(e);
}
});
await(thread, Thread.State.WAITING);
thread.interrupt();
thread.join();
assertNull(exception.get());
}
/**
* Test trying to park with interrupt status set.
*/
@Test
void testInterrupt8() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
LockSupport.park();
assertTrue(Thread.interrupted());
});
}
/**
* Test trying to wait with interrupt status set.
*/
@Test
void testInterrupt9() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
synchronized (lock) {
try {
lock.wait();
fail("wait not interrupted");
} catch (InterruptedException expected) {
assertFalse(Thread.interrupted());
}
}
});
}
/**
* Test trying to block with interrupt status set.
*/
@Test
void testInterrupt10() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
try (Selector sel = Selector.open()) {
sel.select();
assertTrue(Thread.interrupted());
}
});
}
/**
* Test Thread.getName and setName from current thread, started without name.
*/
@Test
void testSetName1() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
assertTrue(me.getName().isEmpty());
me.setName("fred");
assertEquals("fred", me.getName());
});
}
/**
* Test Thread.getName and setName from current thread, started with name.
*/
@Test
void testSetName2() throws Exception {
VThreadRunner.run("fred", () -> {
Thread me = Thread.currentThread();
assertEquals("fred", me.getName());
me.setName("joe");
assertEquals("joe", me.getName());
});
}
/**
* Test Thread.getName and setName from another thread.
*/
@Test
void testSetName3() throws Exception {
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
assertTrue(thread.getName().isEmpty());
// not started
thread.setName("fred1");
assertEquals("fred1", thread.getName());
// started
thread.start();
try {
assertEquals("fred1", thread.getName());
thread.setName("fred2");
assertEquals("fred2", thread.getName());
} finally {
LockSupport.unpark(thread);
thread.join();
}
// terminated
assertEquals("fred2", thread.getName());
thread.setName("fred3");
assertEquals("fred3", thread.getName());
}
/**
* Test Thread.getPriority and setPriority from current thread.
*/
@Test
void testSetPriority1() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
assertEquals(Thread.NORM_PRIORITY, me.getPriority());
me.setPriority(Thread.MAX_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, me.getPriority());
me.setPriority(Thread.NORM_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, me.getPriority());
me.setPriority(Thread.MIN_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, me.getPriority());
assertThrows(IllegalArgumentException.class, () -> me.setPriority(-1));
});
}
/**
* Test Thread.getPriority and setPriority from another thread.
*/
@Test
void testSetPriority2() throws Exception {
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
// not started
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.MAX_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.NORM_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.MIN_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
assertThrows(IllegalArgumentException.class, () -> thread.setPriority(-1));
// running
thread.start();
try {
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.NORM_PRIORITY);
thread.setPriority(Thread.MAX_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.NORM_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
thread.setPriority(Thread.MIN_PRIORITY);
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
assertThrows(IllegalArgumentException.class, () -> thread.setPriority(-1));
} finally {
LockSupport.unpark(thread);
}
thread.join();
// terminated
assertEquals(Thread.NORM_PRIORITY, thread.getPriority());
}
/**
* Test Thread.isDaemon and setDaemon from current thread.
*/
@Test
void testSetDaemon1() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
assertTrue(me.isDaemon());
assertThrows(IllegalThreadStateException.class, () -> me.setDaemon(true));
assertThrows(IllegalArgumentException.class, () -> me.setDaemon(false));
});
}
/**
* Test Thread.isDaemon and setDaemon from another thread.
*/
@Test
void testSetDaemon2() throws Exception {
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
// not started
assertTrue(thread.isDaemon());
thread.setDaemon(true);
assertThrows(IllegalArgumentException.class, () -> thread.setDaemon(false));
// running
thread.start();
try {
assertTrue(thread.isDaemon());
assertThrows(IllegalThreadStateException.class, () -> thread.setDaemon(true));
assertThrows(IllegalArgumentException.class, () -> thread.setDaemon(false));
} finally {
LockSupport.unpark(thread);
}
thread.join();
// terminated
assertTrue(thread.isDaemon());
}
/**
* Test Thread.yield releases carrier thread.
*/
@Test
void testYieldReleasesCarrier() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
var list = new CopyOnWriteArrayList<String>();
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
var thread = factory.newThread(() -> {
list.add("A");
var child = factory.newThread(() -> {
list.add("B");
Thread.yield();
list.add("B");
});
child.start();
Thread.yield();
list.add("A");
try { child.join(); } catch (InterruptedException e) { }
});
thread.start();
thread.join();
}
assertEquals(List.of("A", "B", "A", "B"), list);
}
/**
* Test Thread.yield releases carrier thread when virtual thread holds a monitor.
*/
@Test
@DisabledIf("LockingMode#isLegacy")
void testYieldReleasesCarrierWhenHoldingMonitor() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
var list = new CopyOnWriteArrayList<String>();
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
var lock = new Object();
var thread = factory.newThread(() -> {
list.add("A");
var child = factory.newThread(() -> {
list.add("B");
synchronized (lock) {
Thread.yield();
}
list.add("B");
});
child.start();
Thread.yield();
list.add("A");
try { child.join(); } catch (InterruptedException e) { }
});
thread.start();
thread.join();
}
assertEquals(List.of("A", "B", "A", "B"), list);
}
/**
* Test Thread.yield when thread is pinned.
*/
@Test
void testYieldWhenPinned() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
var list = new CopyOnWriteArrayList<String>();
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
var thread = factory.newThread(() -> {
list.add("A");
var child = factory.newThread(() -> {
list.add("B");
});
child.start();
VThreadPinner.runPinned(() -> {
Thread.yield(); // pinned so will be a no-op
list.add("A");
});
try { child.join(); } catch (InterruptedException e) { }
});
thread.start();
thread.join();
}
assertEquals(List.of("A", "A", "B"), list);
}
/**
* Test Thread.yield does not consume the thread's parking permit.
*/
@Test
void testYieldDoesNotConsumParkingPermit() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
LockSupport.unpark(Thread.currentThread());
Thread.yield();
LockSupport.park(); // should not park
});
thread.join();
}
/**
* Test Thread.yield does not make available the thread's parking permit.
*/
@Test
void testYieldDoesNotOfferParkingPermit() throws Exception {
var thread = Thread.ofVirtual().start(() -> {
Thread.yield();
LockSupport.park(); // should park
});
try {
await(thread, Thread.State.WAITING);
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread.onSpinWait.
*/
@Test
void testOnSpinWait() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
Thread.onSpinWait();
assertTrue(Thread.currentThread() == me);
});
}
/**
* Test Thread.sleep(-1).
*/
@Test
void testSleep1() throws Exception {
VThreadRunner.run(() -> {
assertThrows(IllegalArgumentException.class, () -> Thread.sleep(-1));
assertThrows(IllegalArgumentException.class, () -> Thread.sleep(-1, 0));
assertThrows(IllegalArgumentException.class, () -> Thread.sleep(0, -1));
assertThrows(IllegalArgumentException.class, () -> Thread.sleep(0, 1_000_000));
});
VThreadRunner.run(() -> Thread.sleep(Duration.ofMillis(-1)));
}
/**
* Test Thread.sleep(0).
*/
@Test
void testSleep2() throws Exception {
VThreadRunner.run(() -> Thread.sleep(0));
VThreadRunner.run(() -> Thread.sleep(0, 0));
VThreadRunner.run(() -> Thread.sleep(Duration.ofMillis(0)));
}
/**
* Tasks that sleep for 1 second.
*/
static Stream<ThrowingRunnable> oneSecondSleepers() {
return Stream.of(
() -> Thread.sleep(1000),
() -> Thread.sleep(Duration.ofSeconds(1))
);
}
/**
* Test Thread.sleep duration.
*/
@ParameterizedTest
@MethodSource("oneSecondSleepers")
void testSleep3(ThrowingRunnable sleeper) throws Exception {
VThreadRunner.run(() -> {
long start = millisTime();
sleeper.run();
expectDuration(start, /*min*/900, /*max*/20_000);
});
}
/**
* Tasks that sleep for zero or longer duration.
*/
static Stream<ThrowingRunnable> sleepers() {
return Stream.of(
() -> Thread.sleep(0),
() -> Thread.sleep(0, 0),
() -> Thread.sleep(1000),
() -> Thread.sleep(1000, 0),
() -> Thread.sleep(Duration.ofMillis(0)),
() -> Thread.sleep(Duration.ofMillis(1000))
);
}
/**
* Test Thread.sleep with interrupt status set.
*/
@ParameterizedTest
@MethodSource("sleepers")
void testSleep4(ThrowingRunnable sleeper) throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
try {
sleeper.run();
fail("sleep was not interrupted");
} catch (InterruptedException e) {
// expected
assertFalse(me.isInterrupted());
}
});
}
/**
* Test Thread.sleep with interrupt status set and a negative duration.
*/
@Test
void testSleep4() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
Thread.sleep(Duration.ofMillis(-1000)); // does nothing
assertTrue(me.isInterrupted());
});
}
/**
* Tasks that sleep for a long time.
*/
static Stream<ThrowingRunnable> longSleepers() {
return Stream.of(
() -> Thread.sleep(20_000),
() -> Thread.sleep(20_000, 0),
() -> Thread.sleep(Duration.ofSeconds(20))
);
}
/**
* Test interrupting Thread.sleep.
*/
@ParameterizedTest
@MethodSource("longSleepers")
void testSleep5(ThrowingRunnable sleeper) throws Exception {
VThreadRunner.run(() -> {
Thread t = Thread.currentThread();
scheduleInterrupt(t, 100);
try {
sleeper.run();
fail("sleep was not interrupted");
} catch (InterruptedException e) {
// interrupt status should be cleared
assertFalse(t.isInterrupted());
}
});
}
/**
* Test that Thread.sleep does not disrupt parking permit.
*/
@Test
void testSleep6() throws Exception {
VThreadRunner.run(() -> {
LockSupport.unpark(Thread.currentThread());
long start = millisTime();
Thread.sleep(1000);
expectDuration(start, /*min*/900, /*max*/20_000);
// check that parking permit was not consumed
LockSupport.park();
});
}
/**
* Test that Thread.sleep is not disrupted by unparking thread.
*/
@Test
void testSleep7() throws Exception {
AtomicReference<Exception> exc = new AtomicReference<>();
var thread = Thread.ofVirtual().start(() -> {
try {
long start = millisTime();
Thread.sleep(1000);
expectDuration(start, /*min*/900, /*max*/20_000);
} catch (Exception e) {
exc.set(e);
}
});
// attempt to disrupt sleep
for (int i = 0; i < 5; i++) {
Thread.sleep(20);
LockSupport.unpark(thread);
}
thread.join();
Exception e = exc.get();
if (e != null) {
throw e;
}
}
/**
* Test Thread.sleep when pinned.
*/
@Test
void testSleep8() throws Exception {
VThreadPinner.runPinned(() -> {
long start = millisTime();
Thread.sleep(1000);
expectDuration(start, /*min*/900, /*max*/20_000);
});
}
/**
* Test Thread.sleep when pinned and with interrupt status set.
*/
@Test
void testSleep9() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.interrupt();
try {
VThreadPinner.runPinned(() -> {
Thread.sleep(2000);
});
fail("sleep not interrupted");
} catch (InterruptedException e) {
// expected
assertFalse(me.isInterrupted());
}
});
}
/**
* Test interrupting Thread.sleep when pinned.
*/
@Test
void testSleep10() throws Exception {
VThreadRunner.run(() -> {
Thread t = Thread.currentThread();
scheduleInterrupt(t, 100);
try {
VThreadPinner.runPinned(() -> {
Thread.sleep(20 * 1000);
});
fail("sleep not interrupted");
} catch (InterruptedException e) {
// interrupt status should be cleared
assertFalse(t.isInterrupted());
}
});
}
/**
* Test Thread.sleep(null).
*/
@Test
void testSleep11() throws Exception {
assertThrows(NullPointerException.class, () -> Thread.sleep(null));
VThreadRunner.run(() -> {
assertThrows(NullPointerException.class, () -> Thread.sleep(null));
});
}
/**
* Returns the current time in milliseconds.
*/
private static 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 static void 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");
}
/**
* Test Thread.xxxContextClassLoader from the current thread.
*/
@Test
void testContextClassLoader1() throws Exception {
ClassLoader loader = new ClassLoader() { };
VThreadRunner.run(() -> {
Thread t = Thread.currentThread();
t.setContextClassLoader(loader);
assertTrue(t.getContextClassLoader() == loader);
});
}
/**
* Test inheriting initial value of TCCL from platform thread.
*/
@Test
void testContextClassLoader2() throws Exception {
ClassLoader loader = new ClassLoader() { };
Thread t = Thread.currentThread();
ClassLoader savedLoader = t.getContextClassLoader();
t.setContextClassLoader(loader);
try {
VThreadRunner.run(() -> {
assertTrue(Thread.currentThread().getContextClassLoader() == loader);
});
} finally {
t.setContextClassLoader(savedLoader);
}
}
/**
* Test inheriting initial value of TCCL from virtual thread.
*/
@Test
void testContextClassLoader3() throws Exception {
VThreadRunner.run(() -> {
ClassLoader loader = new ClassLoader() { };
Thread.currentThread().setContextClassLoader(loader);
VThreadRunner.run(() -> {
assertTrue(Thread.currentThread().getContextClassLoader() == loader);
});
});
}
/**
* Test inheriting initial value of TCCL through an intermediate virtual thread.
*/
@Test
void testContextClassLoader4() throws Exception {
ClassLoader loader = new ClassLoader() { };
Thread t = Thread.currentThread();
ClassLoader savedLoader = t.getContextClassLoader();
t.setContextClassLoader(loader);
try {
VThreadRunner.run(() -> {
VThreadRunner.run(() -> {
assertTrue(Thread.currentThread().getContextClassLoader() == loader);
});
});
} finally {
t.setContextClassLoader(savedLoader);
}
}
/**
* Test Thread.xxxContextClassLoader when thread does not inherit the
* initial value of inheritable thread locals.
*/
@Test
void testContextClassLoader5() throws Exception {
VThreadRunner.run(() -> {
ClassLoader loader = new ClassLoader() { };
Thread.currentThread().setContextClassLoader(loader);
int characteristics = VThreadRunner.NO_INHERIT_THREAD_LOCALS;
VThreadRunner.run(characteristics, () -> {
Thread t = Thread.currentThread();
assertTrue(t.getContextClassLoader() == ClassLoader.getSystemClassLoader());
t.setContextClassLoader(loader);
assertTrue(t.getContextClassLoader() == loader);
});
});
}
/**
* Test Thread.setUncaughtExceptionHandler.
*/
@Test
void testUncaughtExceptionHandler1() throws Exception {
class FooException extends RuntimeException { }
var handler = new CapturingUHE();
Thread thread = Thread.ofVirtual().start(() -> {
Thread me = Thread.currentThread();
assertTrue(me.getUncaughtExceptionHandler() == me.getThreadGroup());
me.setUncaughtExceptionHandler(handler);
assertTrue(me.getUncaughtExceptionHandler() == handler);
throw new FooException();
});
thread.join();
assertInstanceOf(FooException.class, handler.exception());
assertEquals(thread, handler.thread());
assertNull(thread.getUncaughtExceptionHandler());
}
/**
* Test default UncaughtExceptionHandler.
*/
@Test
void testUncaughtExceptionHandler2() throws Exception {
class FooException extends RuntimeException { }
var handler = new CapturingUHE();
Thread.UncaughtExceptionHandler savedHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(handler);
Thread thread;
try {
thread = Thread.ofVirtual().start(() -> {
Thread me = Thread.currentThread();
throw new FooException();
});
thread.join();
} finally {
Thread.setDefaultUncaughtExceptionHandler(savedHandler); // restore
}
assertInstanceOf(FooException.class, handler.exception());
assertEquals(thread, handler.thread());
assertNull(thread.getUncaughtExceptionHandler());
}
/**
* Test Thread and default UncaughtExceptionHandler set.
*/
@Test
void testUncaughtExceptionHandler3() throws Exception {
class FooException extends RuntimeException { }
var defaultHandler = new CapturingUHE();
var threadHandler = new CapturingUHE();
Thread.UncaughtExceptionHandler savedHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(defaultHandler);
Thread thread;
try {
thread = Thread.ofVirtual().start(() -> {
Thread me = Thread.currentThread();
assertTrue(me.getUncaughtExceptionHandler() == me.getThreadGroup());
me.setUncaughtExceptionHandler(threadHandler);
assertTrue(me.getUncaughtExceptionHandler() == threadHandler);
throw new FooException();
});
thread.join();
} finally {
Thread.setDefaultUncaughtExceptionHandler(savedHandler); // restore
}
assertInstanceOf(FooException.class, threadHandler.exception());
assertNull(defaultHandler.exception());
assertEquals(thread, threadHandler.thread());
assertNull(thread.getUncaughtExceptionHandler());
}
/**
* Test no Thread or default UncaughtExceptionHandler set.
*/
@Test
void testUncaughtExceptionHandler4() throws Exception {
Thread.UncaughtExceptionHandler savedHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(null);
try {
class FooException extends RuntimeException { }
Thread thread = Thread.ofVirtual().start(() -> {
throw new FooException();
});
thread.join();
assertNull(thread.getUncaughtExceptionHandler());
} finally {
Thread.setDefaultUncaughtExceptionHandler(savedHandler);
}
}
/**
* Test Thread::threadId and getId.
*/
@Test
void testThreadId1() throws Exception {
record ThreadIds(long threadId, long id) { }
var ref = new AtomicReference<ThreadIds>();
Thread vthread = Thread.ofVirtual().unstarted(() -> {
Thread thread = Thread.currentThread();
ref.set(new ThreadIds(thread.threadId(), thread.getId()));
LockSupport.park();
});
// unstarted
long tid = vthread.threadId();
// running
ThreadIds tids;
vthread.start();
try {
while ((tids = ref.get()) == null) {
Thread.sleep(10);
}
assertTrue(tids.threadId() == tid);
assertTrue(tids.id() == tid);
} finally {
LockSupport.unpark(vthread);
vthread.join();
}
// terminated
assertTrue(vthread.threadId() == tid);
assertTrue(vthread.getId() == tid);
}
/**
* Test that each Thread has a unique ID
*/
@Test
void testThreadId2() throws Exception {
// thread ID should be unique
long tid1 = Thread.ofVirtual().unstarted(() -> { }).threadId();
long tid2 = Thread.ofVirtual().unstarted(() -> { }).threadId();
long tid3 = Thread.currentThread().threadId();
assertFalse(tid1 == tid2);
assertFalse(tid1 == tid3);
assertFalse(tid2 == tid3);
}
/**
* Test Thread::getState when thread is new/unstarted.
*/
@Test
void testGetState1() {
var thread = Thread.ofVirtual().unstarted(() -> { });
assertEquals(Thread.State.NEW, thread.getState());
}
/**
* Test Thread::getState when thread is terminated.
*/
@Test
void testGetState2() throws Exception {
var thread = Thread.ofVirtual().start(() -> { });
thread.join();
assertEquals(Thread.State.TERMINATED, thread.getState());
}
/**
* Test Thread::getState when thread is runnable (mounted).
*/
@Test
void testGetState3() throws Exception {
var started = new CountDownLatch(1);
var done = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
started.countDown();
// spin until done
while (!done.get()) {
Thread.onSpinWait();
}
});
try {
// wait for thread to start
started.await();
// thread should be runnable
assertEquals(Thread.State.RUNNABLE, thread.getState());
} finally {
done.set(true);
thread.join();
}
}
/**
* Test Thread::getState when thread is runnable (not mounted).
*/
@Test
void testGetState4() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
AtomicBoolean completed = new AtomicBoolean();
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
Thread thread1 = factory.newThread(() -> {
Thread thread2 = factory.newThread(LockSupport::park);
assertEquals(Thread.State.NEW, thread2.getState());
// start t2 to make it runnable
thread2.start();
try {
assertEquals(Thread.State.RUNNABLE, thread2.getState());
// yield to allow t2 to run and park
Thread.yield();
assertEquals(Thread.State.WAITING, thread2.getState());
} finally {
// unpark t2 to make it runnable again
LockSupport.unpark(thread2);
}
// t2 should be runnable (not mounted)
assertEquals(Thread.State.RUNNABLE, thread2.getState());
completed.set(true);
});
thread1.start();
thread1.join();
}
assertTrue(completed.get() == true);
}
/**
* Test Thread::getState when thread is blocked waiting to enter a monitor.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetState5(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().unstarted(() -> {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
synchronized (lock) { }
});
} else {
ready.set(true);
synchronized (lock) { }
}
});
synchronized (lock) {
thread.start();
awaitTrue(ready);
// wait for thread to block
await(thread, Thread.State.BLOCKED);
}
thread.join();
}
/**
* Test Thread::getState when thread is waiting in Object.wait.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetState6(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
synchronized (lock) {
try {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
lock.wait();
});
} else {
ready.set(true);
lock.wait();
}
} catch (InterruptedException e) { }
}
});
try {
// wait for thread to wait
awaitTrue(ready);
await(thread, Thread.State.WAITING);
// notify, thread should block trying to reenter
synchronized (lock) {
lock.notifyAll();
await(thread, Thread.State.BLOCKED);
}
} finally {
thread.interrupt();
thread.join();
}
}
/**
* Test Thread::getState when thread is waiting in Object.wait(millis).
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetState7(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
synchronized (lock) {
try {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
lock.wait(Long.MAX_VALUE);
});
} else {
ready.set(true);
lock.wait(Long.MAX_VALUE);
}
} catch (InterruptedException e) { }
}
});
try {
// wait for thread to timed-wait
awaitTrue(ready);
await(thread, Thread.State.TIMED_WAITING);
// notify, thread should block trying to reenter
synchronized (lock) {
lock.notifyAll();
await(thread, Thread.State.BLOCKED);
}
} finally {
thread.interrupt();
thread.join();
}
}
/**
* Test Thread::getState when thread is parked.
*/
@Test
void testGetState8() throws Exception {
var thread = Thread.ofVirtual().start(LockSupport::park);
try {
await(thread, Thread.State.WAITING);
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::getState when thread is timed parked.
*/
@Test
void testGetState9() throws Exception {
var thread = Thread.ofVirtual().start(() -> LockSupport.parkNanos(Long.MAX_VALUE));
try {
await(thread, Thread.State.TIMED_WAITING);
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::getState when thread is parked while holding a monitor.
*/
@Test
void testGetState10() throws Exception {
var started = new CountDownLatch(1);
var done = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
started.countDown();
synchronized (lock) {
while (!done.get()) {
LockSupport.park();
}
}
});
try {
// wait for thread to start
started.await();
// wait for thread to park
await(thread, Thread.State.WAITING);
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::getState when thread is timed parked while holding a monitor.
*/
@Test
void testGetState11() throws Exception {
var started = new CountDownLatch(1);
var done = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
started.countDown();
synchronized (lock) {
while (!done.get()) {
LockSupport.parkNanos(Long.MAX_VALUE);
}
}
});
try {
// wait for thread to start
started.await();
// wait for thread to park
await(thread, Thread.State.TIMED_WAITING);
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::isAlive.
*/
@Test
void testIsAlive1() throws Exception {
// unstarted
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
assertFalse(thread.isAlive());
// started
thread.start();
try {
assertTrue(thread.isAlive());
} finally {
LockSupport.unpark(thread);
thread.join();
}
// terminated
assertFalse(thread.isAlive());
}
/**
* Test Thread.holdsLock when lock not held.
*/
@Test
void testHoldsLock1() throws Exception {
VThreadRunner.run(() -> {
var lock = new Object();
assertFalse(Thread.holdsLock(lock));
});
}
/**
* Test Thread.holdsLock when lock held.
*/
@Test
void testHoldsLock2() throws Exception {
VThreadRunner.run(() -> {
var lock = new Object();
synchronized (lock) {
assertTrue(Thread.holdsLock(lock));
}
});
}
/**
* Test Thread.holdsLock when lock held by carrier thread.
*/
@Disabled
@Test
void testHoldsLock3() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
Object lock = new Object();
// carrier thread runs all tasks while holding the lock
ThreadFactory carrierThreadFactory = task -> Thread.ofPlatform().unstarted(() -> {
synchronized (lock) {
task.run();
}
});
try (ExecutorService pool = Executors.newSingleThreadExecutor(carrierThreadFactory)) {
Executor scheduler = task -> pool.submit(task::run);
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
// start virtual that tests if it holds the lock
var result = new AtomicReference<Boolean>();
Thread vthread = factory.newThread(() -> {
result.set(Thread.holdsLock(lock));
});
vthread.start();
vthread.join();
boolean holdsLock = result.get();
assertFalse(holdsLock, "Thread.holdsLock should return false");
}
}
/**
* Test Thread::getStackTrace on unstarted thread.
*/
@Test
void testGetStackTraceUnstarted() {
var thread = Thread.ofVirtual().unstarted(() -> { });
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(stack.length == 0);
}
/**
* Test Thread::getStackTrace on thread that has been started but has not run.
*/
@Test
void testGetStackTraceStarted() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
Executor scheduler = task -> { };
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
Thread thread = factory.newThread(() -> { });
thread.start();
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(stack.length == 0);
}
/**
* Test Thread::getStackTrace on thread that is runnable-mounted.
*/
@Test
void testGetStackTraceRunnableMounted() throws Exception {
var ready = new AtomicBoolean();
var done = new AtomicBoolean();
class Foo {
void spinUntilDone() {
ready.set(true);
while (!done.get()) {
Thread.onSpinWait();
}
}
}
Foo foo = new Foo();
var thread = Thread.ofVirtual().start(foo::spinUntilDone);
try {
awaitTrue(ready);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, Foo.class.getName() + ".spinUntilDone"));
} finally {
done.set(true);
thread.join();
}
}
/**
* Test Thread::getStackTrace on thread that is runnable-unmounted.
*/
@Test
void testGetStackTraceRunnableUnmounted() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
// custom scheduler with one carrier thread
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
// start thread1 to park
Thread thread1 = factory.newThread(LockSupport::park);
thread1.start();
await(thread1, Thread.State.WAITING);
// start thread2 to spin and pin the carrier thread
var started = new AtomicBoolean();
var done = new AtomicBoolean();
Thread thread2 = factory.newThread(() -> {
started.set(true);
while (!done.get()) {
Thread.onSpinWait();
}
});
thread2.start();
awaitTrue(started);
try {
// unpark thread1, it should be "stuck" in runnable state
// (the carrier thread is pinned, no other virtual thread can run)
LockSupport.unpark(thread1);
assertEquals(Thread.State.RUNNABLE, thread1.getState());
// print thread1's stack trace
StackTraceElement[] stack = thread1.getStackTrace();
assertTrue(contains(stack, "LockSupport.park"));
} finally {
done.set(true);
}
}
}
/**
* Test Thread::getStackTrace on thread blocked on monitor enter.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetStackTraceBlocked(boolean pinned) throws Exception {
class Foo {
void enter() {
synchronized (this) { }
}
}
Foo foo = new Foo();
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().unstarted(() -> {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
foo.enter();
});
} else {
ready.set(true);
foo.enter();
}
});
synchronized (foo) {
thread.start();
awaitTrue(ready);
// wait for thread to block
await(thread, Thread.State.BLOCKED);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, Foo.class.getName() + ".enter"));
}
thread.join();
}
/**
* Test Thread::getStackTrace when thread is waiting in Object.wait.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetStackTraceWaiting(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
synchronized (lock) {
try {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
lock.wait();
});
} else {
ready.set(true);
lock.wait();
}
} catch (InterruptedException e) { }
}
});
try {
// wait for thread to wait
awaitTrue(ready);
await(thread, Thread.State.WAITING);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, "Object.wait"));
} finally {
thread.interrupt();
thread.join();
}
}
/**
* Test Thread::getStackTrace when thread is waiting in timed-Object.wait.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetStackTraceTimedWaiting(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
synchronized (lock) {
try {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
lock.wait(Long.MAX_VALUE);
});
} else {
ready.set(true);
lock.wait(Long.MAX_VALUE);
}
} catch (InterruptedException e) { }
}
});
try {
// wait for thread to wait
awaitTrue(ready);
await(thread, Thread.State.TIMED_WAITING);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, "Object.wait"));
} finally {
thread.interrupt();
thread.join();
}
}
/**
* Test Thread::getStackTrace when thread in park.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetStackTraceParked(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var done = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
if (pinned) {
VThreadPinner.runPinned(() -> {
ready.set(true);
while (!done.get()) {
LockSupport.park();
}
});
} else {
ready.set(true);
while (!done.get()) {
LockSupport.park();
}
}
});
try {
// wait for thread to park
awaitTrue(ready);
await(thread, Thread.State.WAITING);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, "LockSupport.park"));
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::getStackTrace when thread in timed-park.
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testGetStackTraceTimedPark(boolean pinned) throws Exception {
var ready = new AtomicBoolean();
var done = new AtomicBoolean();
var thread = Thread.ofVirtual().start(() -> {
if (pinned) {
ready.set(true);
VThreadPinner.runPinned(() -> {
while (!done.get()) {
LockSupport.parkNanos(Long.MAX_VALUE);
}
});
} else {
ready.set(true);
while (!done.get()) {
LockSupport.parkNanos(Long.MAX_VALUE);
}
}
});
try {
// wait for thread to park
awaitTrue(ready);
await(thread, Thread.State.TIMED_WAITING);
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(contains(stack, "LockSupport.parkNanos"));
} finally {
done.set(true);
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test Thread::getStackTrace on terminated thread.
*/
@Test
void testGetStackTraceTerminated() throws Exception {
var thread = Thread.ofVirtual().start(() -> { });
thread.join();
StackTraceElement[] stack = thread.getStackTrace();
assertTrue(stack.length == 0);
}
/**
* Test that Thread.getAllStackTraces does not include virtual threads.
*/
@Test
void testGetAllStackTraces1() throws Exception {
VThreadRunner.run(() -> {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
assertFalse(threads.stream().anyMatch(Thread::isVirtual));
});
}
/**
* Test that Thread.getAllStackTraces includes carrier threads.
*/
@Test
void testGetAllStackTraces2() throws Exception {
assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
try (ForkJoinPool pool = new ForkJoinPool(1)) {
AtomicReference<Thread> ref = new AtomicReference<>();
Executor scheduler = task -> {
pool.submit(() -> {
ref.set(Thread.currentThread());
task.run();
});
};
ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
Thread vthread = factory.newThread(() -> {
synchronized (lock) {
try {
lock.wait();
} catch (Exception e) { }
}
});
vthread.start();
// get carrier Thread
Thread carrier;
while ((carrier = ref.get()) == null) {
Thread.sleep(20);
}
// wait for virtual thread to block in wait
await(vthread, Thread.State.WAITING);
// get all stack traces
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
// allow virtual thread to terminate
synchronized (lock) {
lock.notifyAll();
}
vthread.join();
// stack trace for the carrier thread
StackTraceElement[] stackTrace = map.get(carrier);
assertNotNull(stackTrace);
assertTrue(contains(stackTrace, "java.util.concurrent.ForkJoinPool"));
assertFalse(contains(stackTrace, "java.lang.Object.wait"));
// there should be no stack trace for the virtual thread
assertNull(map.get(vthread));
}
}
private boolean contains(StackTraceElement[] stack, String expected) {
return Stream.of(stack)
.map(Object::toString)
.anyMatch(s -> s.contains(expected));
}
/**
* Test Thread::getThreadGroup on virtual thread created by platform thread.
*/
@Test
void testThreadGroup1() throws Exception {
var thread = Thread.ofVirtual().unstarted(LockSupport::park);
var vgroup = thread.getThreadGroup();
thread.start();
try {
assertEquals(vgroup, thread.getThreadGroup());
} finally {
LockSupport.unpark(thread);
thread.join();
}
assertNull(thread.getThreadGroup());
}
/**
* Test Thread::getThreadGroup on platform thread created by virtual thread.
*/
@Test
void testThreadGroup2() throws Exception {
VThreadRunner.run(() -> {
ThreadGroup vgroup = Thread.currentThread().getThreadGroup();
Thread child = new Thread(() -> { });
ThreadGroup group = child.getThreadGroup();
assertEquals(vgroup, group);
});
}
/**
* Test ThreadGroup returned by Thread::getThreadGroup and subgroup
* created with 2-arg ThreadGroup constructor.
*/
@Test
void testThreadGroup3() throws Exception {
var ref = new AtomicReference<ThreadGroup>();
var thread = Thread.startVirtualThread(() -> {
ref.set(Thread.currentThread().getThreadGroup());
});
thread.join();
ThreadGroup vgroup = ref.get();
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
ThreadGroup group = new ThreadGroup(vgroup, "group");
assertTrue(group.getParent() == vgroup);
assertEquals(Thread.MAX_PRIORITY, group.getMaxPriority());
vgroup.setMaxPriority(Thread.MAX_PRIORITY - 1);
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
assertEquals(Thread.MAX_PRIORITY - 1, group.getMaxPriority());
vgroup.setMaxPriority(Thread.MIN_PRIORITY);
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
assertEquals(Thread.MIN_PRIORITY, group.getMaxPriority());
}
/**
* Test ThreadGroup returned by Thread::getThreadGroup and subgroup
* created with 1-arg ThreadGroup constructor.
*/
@Test
void testThreadGroup4() throws Exception {
VThreadRunner.run(() -> {
ThreadGroup vgroup = Thread.currentThread().getThreadGroup();
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
ThreadGroup group = new ThreadGroup("group");
assertEquals(vgroup, group.getParent());
assertEquals(Thread.MAX_PRIORITY, group.getMaxPriority());
vgroup.setMaxPriority(Thread.MAX_PRIORITY - 1);
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
assertEquals(Thread.MAX_PRIORITY - 1, group.getMaxPriority());
vgroup.setMaxPriority(Thread.MIN_PRIORITY);
assertEquals(Thread.MAX_PRIORITY, vgroup.getMaxPriority());
assertEquals(Thread.MIN_PRIORITY, group.getMaxPriority());
});
}
/**
* Test Thread.enumerate(false).
*/
@Test
void testEnumerate1() throws Exception {
VThreadRunner.run(() -> {
ThreadGroup vgroup = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[100];
int n = vgroup.enumerate(threads, /*recurse*/false);
assertFalse(Arrays.stream(threads, 0, n).anyMatch(Thread::isVirtual));
});
}
/**
* Test Thread.enumerate(true).
*/
@Test
void testEnumerate2() throws Exception {
VThreadRunner.run(() -> {
ThreadGroup vgroup = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[100];
int n = vgroup.enumerate(threads, /*recurse*/true);
assertFalse(Arrays.stream(threads, 0, n).anyMatch(Thread::isVirtual));
});
}
/**
* Test equals and hashCode.
*/
@Test
void testEqualsAndHashCode() throws Exception {
Thread vthread1 = Thread.ofVirtual().unstarted(LockSupport::park);
Thread vthread2 = Thread.ofVirtual().unstarted(LockSupport::park);
// unstarted
assertTrue(vthread1.equals(vthread1));
assertTrue(vthread2.equals(vthread2));
assertFalse(vthread1.equals(vthread2));
assertFalse(vthread2.equals(vthread1));
int hc1 = vthread1.hashCode();
int hc2 = vthread2.hashCode();
vthread1.start();
vthread2.start();
try {
// started, maybe running or parked
assertTrue(vthread1.equals(vthread1));
assertTrue(vthread2.equals(vthread2));
assertFalse(vthread1.equals(vthread2));
assertFalse(vthread2.equals(vthread1));
assertTrue(vthread1.hashCode() == hc1);
assertTrue(vthread2.hashCode() == hc2);
} finally {
LockSupport.unpark(vthread1);
LockSupport.unpark(vthread2);
}
vthread1.join();
vthread2.join();
// terminated
assertTrue(vthread1.equals(vthread1));
assertTrue(vthread2.equals(vthread2));
assertFalse(vthread1.equals(vthread2));
assertFalse(vthread2.equals(vthread1));
assertTrue(vthread1.hashCode() == hc1);
assertTrue(vthread2.hashCode() == hc2);
}
/**
* Test toString on unstarted thread.
*/
@Test
void testToString1() {
Thread thread = Thread.ofVirtual().unstarted(() -> { });
thread.setName("fred");
assertTrue(thread.toString().contains("fred"));
}
/**
* Test toString on running thread.
*/
@Test
void testToString2() throws Exception {
VThreadRunner.run(() -> {
Thread me = Thread.currentThread();
me.setName("fred");
assertTrue(me.toString().contains("fred"));
});
}
/**
* Test toString on parked thread.
*/
@Test
void testToString3() throws Exception {
Thread thread = Thread.ofVirtual().start(() -> {
Thread me = Thread.currentThread();
me.setName("fred");
LockSupport.park();
});
await(thread, Thread.State.WAITING);
try {
assertTrue(thread.toString().contains("fred"));
} finally {
LockSupport.unpark(thread);
thread.join();
}
}
/**
* Test toString on terminated thread.
*/
@Test
void testToString4() throws Exception {
Thread thread = Thread.ofVirtual().start(() -> {
Thread me = Thread.currentThread();
me.setName("fred");
});
thread.join();
assertTrue(thread.toString().contains("fred"));
}
/**
* Thread.UncaughtExceptionHandler that captures the first exception thrown.
*/
private static class CapturingUHE implements Thread.UncaughtExceptionHandler {
Thread thread;
Throwable exception;
@Override
public void uncaughtException(Thread t, Throwable e) {
synchronized (this) {
if (thread == null) {
this.thread = t;
this.exception = e;
}
}
}
Thread thread() {
synchronized (this) {
return thread;
}
}
Throwable exception() {
synchronized (this) {
return exception;
}
}
}
/**
* Waits for the boolean value to become true.
*/
private static void awaitTrue(AtomicBoolean ref) throws Exception {
while (!ref.get()) {
Thread.sleep(20);
}
}
/**
* Waits for the given thread to reach a given state.
*/
private void await(Thread thread, Thread.State expectedState) throws InterruptedException {
Thread.State state = thread.getState();
while (state != expectedState) {
assertTrue(state != Thread.State.TERMINATED, "Thread has terminated");
Thread.sleep(10);
state = thread.getState();
}
}
/**
* Schedule a thread to be interrupted after a delay.
*/
private void scheduleInterrupt(Thread thread, long delayInMillis) {
scheduler.schedule(thread::interrupt, delayInMillis, TimeUnit.MILLISECONDS);
}
}
|