Should I use notify() instaed of notifyAll() in this case?

61 Views Asked by At

I was thinking about this code:

public class SharedVariable<T> {

    private T value;

    public SharedVariable(T init){ 
        this.value = init;
    }

    public synchronized void testAndSet(Predicate<? super T> p, T value)
         throws InterruptedException{ 

       while (!p.test(this.value)){
           this.wait();
           this.value = value;
       }

       this.notifyAll();

    } 
}

Would it be possible to replace .notifyAll() with .notify();? Could problems arise?

1

There are 1 best solutions below

0
On

It depends on how you want to manage locks. notify() wakes up only one thread chosen by thread scheduler. If you have more than two thread sharing the resource, notifyAll() wakes up all of them and one acquires the lock.

Technically, there's no problem if you replace that if the code is simple.