0

I was solving Leetcode problem 1114. I was using wait( ) and notify( ) concept. Using wait() giving time limit exceed but using notifyAll() is giving correct answer.

Why using notify() giving TLE and with notifyAll() it is working fine ??

class Foo {
    private boolean oneDone;
    private boolean twoDone;
    
    public Foo() {
        oneDone = false;
        twoDone = false;
    }

    public synchronized void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        oneDone = true;
        //notify();
        notifyAll();
    }

    public synchronized void second(Runnable printSecond) throws InterruptedException {
        while (!oneDone) {
            wait();
        }
        printSecond.run();
        twoDone = true;
        //notify();
        notifyAll();
    }

    public synchronized void third(Runnable printThird) throws InterruptedException {
        while (!twoDone) {
            wait();
        }
        printThird.run();
    }
}

Why notify() giving TLE but notifyAll() not giving TLE ?

xyz xyz
  • 11
  • 1

1 Answers1

0

The notifyAll() wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods. The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.

The notify() is used to wake up only one randomly chosen thread that’s waiting for an object, and that thread then begins execution. This randomly chosen thread will give up the lock and go back to the waiting state if it is not the next thread, which can lead to deadlocks.

Using notify() in your code can cause a thread to miss the signal and return to a waiting state, which can result in a TLE if the waiting thread does not wake up within the timeout period.

Using notifyAll() wakes up all waiting threads, eliminating the possibility of missing signals and potential deadlocks, allowing your code to run normally.

Feel free
  • 758
  • 5
  • 15
  • So if we have more than two threads then it's better to use notifyAll(). And if we have only two threads then we can use notify(). Correct me if I am wrong ?? – xyz xyz May 04 '23 at 05:34
  • It's safer to use notifyAll() instead of notify() in most cases, regardless of the number of threads involved. Even if you have only two threads, it's possible for one thread to miss the signal and go back to waiting if you use notify() method. So i recommend use notifyAll() in most cases – Feel free May 04 '23 at 05:39
  • More info here -> https://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again – Feel free May 04 '23 at 05:42
  • Glad to help. Don't forget to get to know the knowledge about close/accepted question https://stackoverflow.com/help/accepted-answer – Feel free May 04 '23 at 05:53