0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Marsh
  • 1
  • 1
  • What is the purpose of this `SharedVariable` class? Can you give an example of how it will be used? – Solomon Slow Jul 18 '22 at 12:30
  • 1
    P.S., `testAndSet` is a strange name for what that method does. Most developers would expect a method with that name to either succeed or fail and return _immediately_ in either case. – Solomon Slow Jul 18 '22 at 12:31

1 Answers1

0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197