wait() in Java 24

Dr Heinz M. Kabutz heinz at javaspecialists.eu
Sat Nov 16 13:23:57 UTC 2024


Hi,

I was trying out Object.wait() on Java 24 to see what happens with 
virtual threads and it seems that it now works like ReentrantLock, but 
without resorting to ManagedBlockers.

This code would not print anything prior to Java 24, but works fine now:


import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class ManyWaitingThreads {
     public static void main(String... args) throws InterruptedException {
         var counter = new AtomicInteger();
         var builder = Thread.ofVirtual();
         for (int i = 0; i < 100_000; i++) {
             builder.start(() -> {
                 synchronized (ManyWaitingThreads.class) {
                     try {
                         counter.incrementAndGet();
                         ManyWaitingThreads.class.wait();
                     } catch (InterruptedException e) {
                         throw new CancellationException("interrupted");
                     }
                 }
             });
         }
         builder.start(() -> System.out.println("All threads waiting"));
         while(counter.get() < 100_000) Thread.yield();
         synchronized (ManyWaitingThreads.class) {
             ManyWaitingThreads.class.notifyAll();
         }
     }
}

I seemed to have missed this new change, but it is very welcome. Thanks 
for all your hard work.

Regards

Heinz
-- 
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java™ Specialists' Newsletter" - www.javaspecialists.eu
Java Champion - www.javachampions.org
JavaOne Rock Star Speaker
Tel: +30 69 75 595 262
Skype: kabutz



More information about the loom-dev mailing list