Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wake up all threads waiting on same condition?

I have a following scenario. Several threads are waiting on the same condition. And when are notified, all should stop waiting, change flag and return object:

 public Object getObject(){
    lock.lock();
    try {
        while (check)){
            condition.await();
        }

        return returnObjectAndSetCheckToFalse();
    } finally {
        lock.unlock();
    }
}

however this code does not work, since faster thread could change check flag to false, and second slower thread will block again. It is possible to have a logic that both waiting threads will be awaken, they both will set check flag to false, and return object? Or maybe it is contradictory?

The easiest way would be to change wait to if statement, however this would be vulnerable to spurious wakeup.

like image 892
gomul Avatar asked Dec 28 '25 07:12

gomul


1 Answers

You could use CountDownLatch or a CyclicBarrier.

Using a Future is also a possibility, a FutureTask to be more specific. It has a conveniance method get() which can be used to block code execution until the Future has completed its job, thus fulfilling your requirements.

You could also implement your own Barrier which would do wait() in a loop until a certain condition has been met. Fulfilling that condition would trigger notifyAll(), loop would finish and all threads could continue. But that would be reinventing the wheel.

like image 56
Dariusz Avatar answered Dec 30 '25 21:12

Dariusz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!