1
1
/*
2
- * Copyright (c) 2022, 2024 , Oracle and/or its affiliates. All rights reserved.
2
+ * Copyright (c) 2022, 2025 , Oracle and/or its affiliates. All rights reserved.
3
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
4
*
5
5
* This code is free software; you can redistribute it and/or modify it
47
47
import java .lang .management .ThreadMXBean ;
48
48
import java .util .Arrays ;
49
49
import java .util .concurrent .CyclicBarrier ;
50
+ import java .util .concurrent .atomic .AtomicBoolean ;
50
51
import java .util .stream .Stream ;
51
52
import jdk .test .lib .thread .VThreadRunner ; // ensureParallelism requires jdk.management
52
53
@@ -55,6 +56,8 @@ public class VirtualThreadDeadlocks {
55
56
private static final Object LOCK2 = new Object ();
56
57
57
58
private static final CyclicBarrier barrier = new CyclicBarrier (2 );
59
+ private static final AtomicBoolean reached1 = new AtomicBoolean ();
60
+ private static final AtomicBoolean reached2 = new AtomicBoolean ();
58
61
59
62
/**
60
63
* PP = test deadlock with two platform threads
@@ -72,6 +75,7 @@ public static void main(String[] args) throws Exception {
72
75
Thread thread1 = builder1 .start (() -> {
73
76
synchronized (LOCK1 ) {
74
77
try { barrier .await (); } catch (Exception ie ) {}
78
+ reached1 .set (true );
75
79
synchronized (LOCK2 ) { }
76
80
}
77
81
});
@@ -84,14 +88,15 @@ public static void main(String[] args) throws Exception {
84
88
Thread thread2 = builder2 .start (() -> {
85
89
synchronized (LOCK2 ) {
86
90
try { barrier .await (); } catch (Exception ie ) {}
91
+ reached2 .set (true );
87
92
synchronized (LOCK1 ) { }
88
93
}
89
94
});
90
95
System .out .println ("thread2 => " + thread2 );
91
96
92
97
System .out .println ("Waiting for thread1 and thread2 to deadlock ..." );
93
- awaitBlocked (thread1 );
94
- awaitBlocked (thread2 );
98
+ awaitTrueAndBlocked (thread1 , reached1 );
99
+ awaitTrueAndBlocked (thread2 , reached2 );
95
100
96
101
ThreadMXBean bean = ManagementFactory .getPlatformMXBean (ThreadMXBean .class );
97
102
long [] deadlockedThreads = sorted (bean .findMonitorDeadlockedThreads ());
@@ -108,8 +113,8 @@ public static void main(String[] args) throws Exception {
108
113
throw new RuntimeException ("Unexpected result" );
109
114
}
110
115
111
- private static void awaitBlocked (Thread thread ) throws InterruptedException {
112
- while (thread .getState () != Thread .State .BLOCKED ) {
116
+ private static void awaitTrueAndBlocked (Thread thread , AtomicBoolean flag ) throws InterruptedException {
117
+ while (! flag . get () || thread .getState () != Thread .State .BLOCKED ) {
113
118
Thread .sleep (10 );
114
119
if (!thread .isAlive ()) {
115
120
throw new RuntimeException ("Thread " + thread + " is terminated." );
0 commit comments