4343
4444import com .sun .management .GarbageCollectionNotificationInfo ;
4545
46+ import static java .util .concurrent .TimeUnit .SECONDS ;
47+ import static java .util .concurrent .TimeUnit .NANOSECONDS ;
48+
4649public class TestCycleEndMessage {
4750
4851 public static void main (String [] args ) throws Exception {
4952 final AtomicBoolean foundGenerationInCycle = new AtomicBoolean (false );
53+ final AtomicBoolean oneCycleCompleted = new AtomicBoolean (false );
54+
55+ final Object lock = new Object ();
5056
5157 NotificationListener listener = new NotificationListener () {
5258 @ Override
@@ -59,9 +65,15 @@ public void handleNotification(Notification n, Object o) {
5965
6066 System .out .println ("Received: " + name + " / " + action );
6167
62- if (name .equals ("Shenandoah Cycles" ) &&
63- (action .contains ("Global" ) || action .contains ("Young" ) || action .contains ("Old" ))) {
64- foundGenerationInCycle .set (true );
68+ if (name .equals ("Shenandoah Cycles" )) {
69+ oneCycleCompleted .set (true );
70+
71+ if ((action .contains ("Global" ) || action .contains ("Young" ) || action .contains ("Old" ))) {
72+ foundGenerationInCycle .set (true );
73+ }
74+ synchronized (lock ) {
75+ lock .notifyAll ();
76+ }
6577 }
6678 }
6779 }
@@ -71,8 +83,21 @@ public void handleNotification(Notification n, Object o) {
7183 ((NotificationEmitter ) bean ).addNotificationListener (listener , null , null );
7284 }
7385
74- System .gc ();
75- Thread .sleep (2000 );
86+ synchronized (lock ) {
87+ System .gc ();
88+ long deadline = System .nanoTime () + SECONDS .toNanos (5 );
89+ while (!oneCycleCompleted .get ()) {
90+ long remaining = NANOSECONDS .toMillis (deadline - System .nanoTime ());
91+ if (remaining <= 0 ) {
92+ break ;
93+ }
94+ lock .wait (remaining );
95+ }
96+ }
97+
98+ if (!oneCycleCompleted .get ()) {
99+ throw new IllegalStateException ("Test did not complete at least one GC cycle" );
100+ }
76101
77102 if (!foundGenerationInCycle .get ()) {
78103 throw new IllegalStateException ("Expected to find generation name (Global/Young/Old) in Shenandoah Cycles action message" );
0 commit comments