Java notify () is called before waiting ()

Is it possible for notify () in another thread to be called before wait () in one thread? This is happening to me.

The client requests a value from the target and expects an RV result variable. In case the goal is the client itself, I update the RV with the correct result and call notify () on the 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 requestor has completed the entire “network” (sendReqest in the above example) with itself, the result will be updated in the result variable. When the requesting thread now calls wait (), the program will not continue because the notification has already been called.

How can we prevent this?

+5
source share
4 answers

notify , wait ed .

, , - . :

synchronized (results) {
    while (!results.hasResults()) {
        // no results yet; wait for them
        try {
            results.wait();
        } catch (InterruptedException ie) { /* ignore */ }
    }
}
+4

.

Java Future , , FutureTask .

FutureTask, . -.

+1

, () , :)

class EMU{
    ResultVar RV;
    Address my_address;
    volatile boolean condition = true;

    ResultVar findValue(String key){
        String tgt = findTarget(key);
        sendRequest(tgt, key);
        synchronized(RV){
            while(condition == true)
            {
                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){
                    condition = false;
                    RV.notify();
                }
            }
        }

    };
0

All Articles