11/*
2- * Copyright (c) 2022, 2023 , Oracle and/or its affiliates. All rights reserved.
2+ * Copyright (c) 2022, 2025 , Oracle and/or its affiliates. All rights reserved.
33 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44 *
55 * This code is free software; you can redistribute it and/or modify it
4747import java .lang .management .ThreadMXBean ;
4848import java .util .Arrays ;
4949import java .util .concurrent .CyclicBarrier ;
50+ import java .util .concurrent .atomic .AtomicBoolean ;
5051import java .util .stream .Stream ;
5152import jdk .test .lib .thread .VThreadRunner ;
5253
@@ -55,6 +56,8 @@ public class VirtualThreadDeadlocks {
5556 private static final Object LOCK2 = new Object ();
5657
5758 private static final CyclicBarrier barrier = new CyclicBarrier (2 );
59+ private static final AtomicBoolean reached1 = new AtomicBoolean ();
60+ private static final AtomicBoolean reached2 = new AtomicBoolean ();
5861
5962 /**
6063 * PP = test deadlock with two platform threads
@@ -72,6 +75,7 @@ public static void main(String[] args) throws Exception {
7275 Thread thread1 = builder1 .start (() -> {
7376 synchronized (LOCK1 ) {
7477 try { barrier .await (); } catch (Exception ie ) {}
78+ reached1 .set (true );
7579 synchronized (LOCK2 ) { }
7680 }
7781 });
@@ -84,14 +88,15 @@ public static void main(String[] args) throws Exception {
8488 Thread thread2 = builder2 .start (() -> {
8589 synchronized (LOCK2 ) {
8690 try { barrier .await (); } catch (Exception ie ) {}
91+ reached2 .set (true );
8792 synchronized (LOCK1 ) { }
8893 }
8994 });
9095 System .out .println ("thread2 => " + thread2 );
9196
9297 System .out .println ("Waiting for thread1 and thread2 to deadlock ..." );
93- awaitBlocked (thread1 );
94- awaitBlocked (thread2 );
98+ awaitTrueAndBlocked (thread1 , reached1 );
99+ awaitTrueAndBlocked (thread2 , reached2 );
95100
96101 ThreadMXBean bean = ManagementFactory .getPlatformMXBean (ThreadMXBean .class );
97102 long [] deadlockedThreads = sorted (bean .findMonitorDeadlockedThreads ());
@@ -108,8 +113,8 @@ public static void main(String[] args) throws Exception {
108113 throw new RuntimeException ("Unexpected result" );
109114 }
110115
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 ) {
113118 Thread .sleep (10 );
114119 if (!thread .isAlive ()) {
115120 throw new RuntimeException ("Thread " + thread + " is terminated." );
0 commit comments