File: MonitorWaitNotify.java

package info (click to toggle)
openjdk-24 24.0.2%2B12-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 831,900 kB
  • sloc: java: 5,677,020; cpp: 1,323,154; xml: 1,320,524; ansic: 486,889; asm: 405,131; objc: 21,025; sh: 15,221; javascript: 11,049; python: 8,222; makefile: 2,504; perl: 357; awk: 351; sed: 172; pascal: 103; exp: 54; jsp: 24; csh: 3
file content (861 lines) | stat: -rw-r--r-- 28,498 bytes parent folder | download
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
/*
 * 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
 * @summary Test virtual threads using Object.wait/notifyAll
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=LM_LEGACY
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -XX:LockingMode=1 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=LM_LIGHTWEIGHT
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -XX:LockingMode=2 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xint-LM_LEGACY
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xint -XX:LockingMode=1 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xint-LM_LIGHTWEIGHT
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xint -XX:LockingMode=2 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-LM_LEGACY
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:LockingMode=1 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-LM_LIGHTWEIGHT
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:LockingMode=2 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-TieredStopAtLevel1-LM_LEGACY
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:TieredStopAtLevel=1 -XX:LockingMode=1 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-TieredStopAtLevel1-LM_LIGHTWEIGHT
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:TieredStopAtLevel=1 -XX:LockingMode=2 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-noTieredCompilation-LM_LEGACY
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:-TieredCompilation -XX:LockingMode=1 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

/*
 * @test id=Xcomp-noTieredCompilation-LM_LIGHTWEIGHT
 * @modules java.base/java.lang:+open jdk.management
 * @library /test/lib
 * @build LockingMode
 * @run junit/othervm -Xcomp -XX:-TieredCompilation -XX:LockingMode=2 --enable-native-access=ALL-UNNAMED MonitorWaitNotify
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.Collectors;

import jdk.test.lib.thread.VThreadScheduler;
import jdk.test.lib.thread.VThreadRunner;   // ensureParallelism requires jdk.management
import jdk.test.lib.thread.VThreadPinner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.condition.DisabledIf;
import org.junit.jupiter.params.provider.Arguments;
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 MonitorWaitNotify {

    @BeforeAll
    static void setup() {
        // need >=2 carriers for testing pinning
        VThreadRunner.ensureParallelism(2);
    }

    /**
     * Test virtual thread waits, notified by platform thread.
     */
    @ParameterizedTest
    @ValueSource(booleans = { true, false })
    void testWaitNotify1(boolean pinned) throws Exception {
        var lock = new Object();
        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) { }
            }
        });
        awaitTrue(ready);

        // notify, thread should block waiting to reenter
        synchronized (lock) {
            lock.notifyAll();
            await(thread, Thread.State.BLOCKED);
        }
        thread.join();
    }

    /**
     * Test platform thread waits, notified by virtual thread.
     */
    @Test
    void testWaitNotify2() throws Exception {
        var lock = new Object();
        var thread = Thread.ofVirtual().unstarted(() -> {
            synchronized (lock) {
                lock.notifyAll();
            }
        });
        synchronized (lock) {
            thread.start();
            lock.wait();
        }
        thread.join();
    }

    /**
     * Test virtual thread waits, notified by another virtual thread.
     */
    @ParameterizedTest
    @ValueSource(booleans = { true, false })
    void testWaitNotify3(boolean pinned) throws Exception {
        var lock = new Object();
        var ready = new AtomicBoolean();
        var thread1 = Thread.ofVirtual().start(() -> {
            synchronized (lock) {
                try {
                    if (pinned) {
                        VThreadPinner.runPinned(() -> {
                            ready.set(true);
                            lock.wait();
                        });
                    } else {
                        ready.set(true);
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        var thread2 = Thread.ofVirtual().start(() -> {
            try {
                awaitTrue(ready);

                // notify, thread should block waiting to reenter
                synchronized (lock) {
                    lock.notifyAll();
                    await(thread1, Thread.State.BLOCKED);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.join();
        thread2.join();
    }

    /**
     * Test notifyAll when there are no threads waiting.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    void testNotifyBeforeWait(int timeout) throws Exception {
        var lock = new Object();

        // no threads waiting
        synchronized (lock) {
            lock.notifyAll();
        }

        var ready = new AtomicBoolean();
        var thread = Thread.ofVirtual().start(() -> {
            try {
                synchronized (lock) {
                    ready.set(true);

                    // thread should wait
                    if (timeout > 0) {
                        lock.wait(timeout);
                    } else {
                        lock.wait();
                    }
                }
            } catch (InterruptedException e) { }
        });

        try {
            // wait for thread to start and wait
            awaitTrue(ready);
            Thread.State expectedState = timeout > 0
                    ? Thread.State.TIMED_WAITING
                    : Thread.State.WAITING;
            await(thread, expectedState);

            // poll thread state again, it should still be waiting
            Thread.sleep(10);
            assertEquals(thread.getState(), expectedState);
        } finally {
            synchronized (lock) {
                lock.notifyAll();
            }
            thread.join();
        }
    }

    /**
     * Returns a stream of elements that are ordered pairs of platform and virtual thread
     * counts. 0,2,4,..8 platform threads. 2,4,6,..16 virtual threads.
     */
    static Stream<Arguments> threadCounts() {
        return IntStream.range(0, 9)
                .filter(i -> i % 2 == 0)
                .mapToObj(i -> i)
                .flatMap(np -> IntStream.range(2, 17)
                        .filter(i -> i % 2 == 0)
                        .mapToObj(vp -> Arguments.of(np, vp)));
    }

    /**
     * Test notify wakes only one thread when platform and virtual threads are waiting.
     */
    @ParameterizedTest
    @MethodSource("threadCounts")
    @DisabledIf("LockingMode#isLegacy")
    void testNotifyOneThread(int nPlatformThreads, int nVirtualThreads) throws Exception {
        int nThreads = nPlatformThreads + nVirtualThreads;

        var lock = new Object();
        var ready = new CountDownLatch(nThreads);
        var notified = new AtomicInteger();

        Runnable waitTask = () -> {
            synchronized (lock) {
                try {
                    ready.countDown();
                    lock.wait();
                    notified.incrementAndGet();
                } catch (InterruptedException e) { }
            }
        };

        var threads = new ArrayList<Thread>();
        try {
            for (int i = 0; i < nPlatformThreads; i++) {
                threads.add(Thread.ofPlatform().start(waitTask));
            }
            for (int i = 0; i < nVirtualThreads; i++) {
                threads.add(Thread.ofVirtual().start(waitTask));
            }

            // wait for all threads to wait
            ready.await();

            // wake threads, one by one
            for (int i = 0; i < threads.size(); i++) {

                // wake one thread
                synchronized (lock) {
                    lock.notify();
                }

                // one thread should have awoken
                int expectedWakeups = i + 1;
                while (notified.get() < expectedWakeups) {
                    Thread.sleep(10);
                }
                assertEquals(expectedWakeups, notified.get());
            }
        } finally {
            for (Thread t : threads) {
                t.interrupt();
                t.join();
            }
        }
    }

    /**
     * Test notifyAll wakes all threads.
     */
    @ParameterizedTest
    @MethodSource("threadCounts")
    @DisabledIf("LockingMode#isLegacy")
    void testNotifyAllThreads(int nPlatformThreads, int nVirtualThreads) throws Exception {
        int nThreads = nPlatformThreads + nVirtualThreads;

        var lock = new Object();
        var ready = new CountDownLatch(nThreads);
        var notified = new CountDownLatch(nThreads);

        Runnable waitTask = () -> {
            synchronized (lock) {
                try {
                    ready.countDown();
                    lock.wait();
                    notified.countDown();
                } catch (InterruptedException e) { }
            }
        };

        var threads = new ArrayList<Thread>();
        try {
            for (int i = 0; i < nPlatformThreads; i++) {
                threads.add(Thread.ofPlatform().start(waitTask));
            }
            for (int i = 0; i < nVirtualThreads; i++) {
                threads.add(Thread.ofVirtual().start(waitTask));
            }

            // wait for all threads to wait
            ready.await();

            // wakeup all threads
            synchronized (lock) {
                lock.notifyAll();
            }

            // wait for all threads to have awoken
            notified.await();

        } finally {
            for (Thread t : threads) {
                t.interrupt();
                t.join();
            }
        }
    }

    /**
     * Test duration of timed Object.wait.
     */
    @Test
    void testTimedWaitDuration1() throws Exception {
        var lock = new Object();

        var durationRef = new AtomicReference<Long>();
        var thread = Thread.ofVirtual().start(() -> {
            try {
                synchronized (lock) {
                    long start = millisTime();
                    lock.wait(2000);
                    durationRef.set(millisTime() - start);
                }
            } catch (InterruptedException e) { }
        });

        thread.join();

        long duration = durationRef.get();
        checkDuration(duration, 1900, 20_000);
    }

    /**
     * Test duration of timed Object.wait. This test invokes wait twice, first with a short
     * timeout, the second with a longer timeout. The test scenario ensures that the
     * timeout from the first wait doesn't interfere with the second wait.
     */
    @Test
    void testTimedWaitDuration2() throws Exception {
        var lock = new Object();

        var ready = new AtomicBoolean();
        var waited = new AtomicBoolean();
        var durationRef = new AtomicReference<Long>();
        var thread = Thread.ofVirtual().start(() -> {
            try {
                synchronized (lock) {
                    ready.set(true);
                    lock.wait(200);
                    waited.set(true);

                    long start = millisTime();
                    lock.wait(2000);
                    durationRef.set(millisTime() - start);
                }
            } catch (InterruptedException e) { }
        });

        awaitTrue(ready);
        synchronized (lock) {
            // wake thread if waiting in first wait
            if (!waited.get()) {
                lock.notifyAll();
            }
        }

        thread.join();

        long duration = durationRef.get();
        checkDuration(duration, 1900, 20_000);
    }

    /**
     * Testing invoking Object.wait with interrupt status set.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    void testWaitWithInterruptSet(int timeout) throws Exception {
        VThreadRunner.run(() -> {
            Object lock = new Object();
            synchronized (lock) {
                Thread.currentThread().interrupt();
                if (timeout > 0) {
                    assertThrows(InterruptedException.class, () -> lock.wait(timeout));
                } else {
                    assertThrows(InterruptedException.class, lock::wait);
                }
                assertFalse(Thread.currentThread().isInterrupted());
            }
        });
    }

    /**
     * Test interrupting a virtual thread waiting in Object.wait.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    void testInterruptWait(int timeout) throws Exception {
        var lock = new Object();
        var ready = new AtomicBoolean();
        var interruptedException = new AtomicBoolean();
        var vthread = Thread.ofVirtual().start(() -> {
            synchronized (lock) {
                try {
                    ready.set(true);
                    if (timeout > 0) {
                        lock.wait(timeout);
                    } else {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    // check stack trace has the expected frames
                    Set<String> expected = Set.of("wait0", "wait", "run");
                    Set<String> methods = Stream.of(e.getStackTrace())
                            .map(StackTraceElement::getMethodName)
                            .collect(Collectors.toSet());
                    assertTrue(methods.containsAll(expected));

                    interruptedException.set(true);
                }
            }
        });

        // wait for thread to start and wait
        awaitTrue(ready);
        await(vthread, timeout > 0 ? Thread.State.TIMED_WAITING : Thread.State.WAITING);

        // interrupt thread, should block, then throw InterruptedException
        synchronized (lock) {
            vthread.interrupt();
            await(vthread, Thread.State.BLOCKED);
        }
        vthread.join();
        assertTrue(interruptedException.get());
    }

    /**
     * Test interrupting a virtual thread blocked waiting to reenter after waiting.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    void testInterruptReenterAfterWait(int timeout) throws Exception {
        var lock = new Object();
        var ready = new AtomicBoolean();
        var interruptedException = new AtomicBoolean();
        var vthread = Thread.ofVirtual().start(() -> {
            synchronized (lock) {
                try {
                    ready.set(true);
                    if (timeout > 0) {
                        lock.wait(timeout);
                    } else {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    interruptedException.set(true);
                }
            }
        });

        // wait for thread to start and wait
        awaitTrue(ready);
        await(vthread, timeout > 0 ? Thread.State.TIMED_WAITING : Thread.State.WAITING);

        // notify, thread should block waiting to reenter
        synchronized (lock) {
            lock.notifyAll();
            await(vthread, Thread.State.BLOCKED);

            // interrupt when blocked
            vthread.interrupt();
        }

        vthread.join();
        assertFalse(interruptedException.get());
        assertTrue(vthread.isInterrupted());
    }

    /**
     * Test Object.wait when the monitor entry count > 1.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    void testWaitWhenEnteredManyTimes(int timeout) throws Exception {
        var lock = new Object();
        var ready = new AtomicBoolean();
        var vthread = Thread.ofVirtual().start(() -> {
            synchronized (lock) {
                synchronized (lock) {
                    synchronized (lock) {
                        try {
                            ready.set(true);
                            if (timeout > 0) {
                                lock.wait(timeout);
                            } else {
                                lock.wait();
                            }
                        } catch (InterruptedException e) { }
                    }
                }
            }
        });

        // wait for thread to start and wait
        awaitTrue(ready);
        await(vthread, timeout > 0 ? Thread.State.TIMED_WAITING : Thread.State.WAITING);

        // notify, thread should block waiting to reenter
        synchronized (lock) {
            lock.notifyAll();
            await(vthread, Thread.State.BLOCKED);
        }
        vthread.join();
    }

    /**
     * Test that Object.wait does not consume the thread's parking permit.
     */
    @Test
    void testParkingPermitNotConsumed() throws Exception {
        var lock = new Object();
        var started = new CountDownLatch(1);
        var completed = new AtomicBoolean();
        var vthread = Thread.ofVirtual().start(() -> {
            started.countDown();
            LockSupport.unpark(Thread.currentThread());
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    fail("wait interrupted");
                }
            }
            LockSupport.park();      // should not park
            completed.set(true);
        });

        // wait for thread to start and wait
        started.await();
        await(vthread, Thread.State.WAITING);

        // wakeup thread
        synchronized (lock) {
            lock.notifyAll();
        }

        // thread should terminate
        vthread.join();
        assertTrue(completed.get());
    }

    /**
     * Test that Object.wait does not make available the thread's parking permit.
     */
    @Test
    void testParkingPermitNotOffered() throws Exception {
        var lock = new Object();
        var started = new CountDownLatch(1);
        var readyToPark = new CountDownLatch(1);
        var completed = new AtomicBoolean();
        var vthread = Thread.ofVirtual().start(() -> {
            started.countDown();
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    fail("wait interrupted");
                }
            }
            readyToPark.countDown();
            LockSupport.park();      // should park
            completed.set(true);
        });

        // wait for thread to start and wait
        started.await();
        await(vthread, Thread.State.WAITING);

        // wakeup thread
        synchronized (lock) {
            lock.notifyAll();
        }

        // thread should park
        readyToPark.await();
        await(vthread, Thread.State.WAITING);

        LockSupport.unpark(vthread);

        // thread should terminate
        vthread.join();
        assertTrue(completed.get());
    }

    /**
     * Test that Object.wait releases the carrier. This test uses a custom scheduler
     * with one carrier thread.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 30000, Integer.MAX_VALUE })
    @DisabledIf("LockingMode#isLegacy")
    void testReleaseWhenWaiting1(int timeout) throws Exception {
        assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
        try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
            ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);

            var lock = new Object();
            var ready = new AtomicBoolean();
            var completed = new AtomicBoolean();

            var vthread1 = factory.newThread(() -> {
                synchronized (lock) {
                    try {
                        ready.set(true);
                        if (timeout > 0) {
                            lock.wait(timeout);
                        } else {
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        fail("wait interrupted");
                    }
                }
                completed.set(true);
            });
            vthread1.start();

            // wait for vthread1 to start and wait
            awaitTrue(ready);
            await(vthread1, timeout > 0 ? Thread.State.TIMED_WAITING : Thread.State.WAITING);

            // carrier should be released, use it for another thread
            var executed = new AtomicBoolean();
            var vthread2 = factory.newThread(() -> {
                executed.set(true);
            });
            vthread2.start();
            vthread2.join();
            assertTrue(executed.get());

            // wakeup vthread1
            synchronized (lock) {
                lock.notifyAll();
            }

            vthread1.join();
            assertTrue(completed.get());
        }
    }

    /**
     * Test that Object.wait releases the carrier. This test arranges for 4*ncores - 1
     * virtual threads to wait. For long timeout and no timeout cases, all virtual threads
     * will wait until they are notified.
     */
    @ParameterizedTest
    @ValueSource(ints = { 0, 10, 20, 100, 500, 30000, Integer.MAX_VALUE })
    @DisabledIf("LockingMode#isLegacy")
    void testReleaseWhenWaiting2(int timeout) throws Exception {
        int VTHREAD_COUNT = 4 * Runtime.getRuntime().availableProcessors();
        CountDownLatch latch = new CountDownLatch(VTHREAD_COUNT);
        Object lock = new Object();
        AtomicInteger counter = new AtomicInteger(0);

        for (int i = 0; i < VTHREAD_COUNT; i++) {
            Thread.ofVirtual().name("vthread-" + i).start(() -> {
                synchronized (lock) {
                    if (counter.incrementAndGet() == VTHREAD_COUNT) {
                        lock.notifyAll();
                    } else {
                        try {
                            if (timeout > 0) {
                                lock.wait(timeout);
                            } else {
                                lock.wait();
                            }
                        } catch (InterruptedException e) {}
                    }
                }
                latch.countDown();
            });
        }
        latch.await();
    }

    /**
     * Test that wait(long) throws IAE when timeout is negative.
     */
    @Test
    void testIllegalArgumentException() throws Exception {
        VThreadRunner.run(() -> {
            Object obj = new Object();
            synchronized (obj) {
                assertThrows(IllegalArgumentException.class, () -> obj.wait(-1L));
                assertThrows(IllegalArgumentException.class, () -> obj.wait(-1000L));
                assertThrows(IllegalArgumentException.class, () -> obj.wait(Long.MIN_VALUE));
            }
        });
    }

    /**
     * Test that wait throws IMSE when not owner.
     */
    @Test
    void testIllegalMonitorStateException() throws Exception {
        VThreadRunner.run(() -> {
            Object obj = new Object();
            assertThrows(IllegalMonitorStateException.class, () -> obj.wait());
            assertThrows(IllegalMonitorStateException.class, () -> obj.wait(0));
            assertThrows(IllegalMonitorStateException.class, () -> obj.wait(1000));
            assertThrows(IllegalMonitorStateException.class, () -> obj.wait(Long.MAX_VALUE));
        });
    }

    /**
     * Waits for the boolean value to become true.
     */
    private static void awaitTrue(AtomicBoolean ref) throws InterruptedException {
        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();
        }
    }

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

    /**
     * Check a duration is within expected bounds.
     * @param duration, 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 checkDuration(long duration, long min, long max) {
        assertTrue(duration >= min,
                "Duration " + duration + "ms, expected >= " + min + "ms");
        assertTrue(duration <= max,
                "Duration " + duration + "ms, expected <= " + max + "ms");
    }
}