Java notify() gets called before wait()

sgarg picture sgarg · May 1, 2012 · Viewed 8.9k times · Source

Isn't it possible that notify() in another thread gets called before the wait() in one thread? It's happening with me.

A client requests a value from a target and waits on a result variable RV. In case the target is the client itself, I update RV with the correct result and call notify() on RV in another thread.

class EMU {

  ResultVar RV;
  Address my_address;

  ResultVar findValue(String key) {
    String tgt = findTarget(key);
    sendRequest(tgt, key);
    synchronized(RV) {
      RV.wait();
    }

    return RV;
  }

  Runnable Server = new Runnable() {
    public void run() {
      //code to receive connections. Assume object of type Request is read from the stream.
      Request r = (Request) ois.readObject();
      if(r.requesterAddr.compareTo(my_address) == 0) {
        String val = findVal(key);
        RV.putVal(val);
        synchronized(RV){
          RV.notify();
        }
      }
    }
  };
}

The problem is that before the requester has completed all the "networking" (sendReqest in the above example) with itself, the result is updated in the result variable. When the requester thread now calls wait(), the program doesn't continue, since notify has already been called.

How can we prevent it?

Answer

Walter Laan picture Walter Laan · May 1, 2012

You check some flag before waiting (in a loop), see the tutorial: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html