Call Object.notify () before Object.wait ()

If there is no waiting thread using Object.wait(), any calls Object.notify()or Object.notifyAll()will not have any effect. I have a scenario in which if I call Object.notify()when the wait set is empty, the subsequent call Object.wait()should not put the thread on hold. How can I do that? Semaphores can be one of the solutions that I can think of. Is there a more elegant solution?

+5
source share
4 answers

This kind of scenario seems to be perfect for Semaphore. Call Semaphore.release()instead notify()and Semaphore.acquire()instead of waiting.

+7
source

. .

boolean stopped = false;

public void run(){
   synchronized(object){
      while(!stopped)
        object.wait();
   }

}

public void stop(){
  synchronized(object){
    stopped=true;
    object.notify();
  }

}
+7

Semaphore, CyclicBarrier , , CountDownLatch - , . , , , ( ).

+4

:

 req.run();
synchronized (req) {
                    try {
                        req.wait(3000);
                        rawResponse = eq.ReturnXML;
                        logger.info("[" + refID + "] Response recieved: " + rawResponse);
                        responseRecieved = true;
                        req.notify();
                    } catch (InterruptedException ex) {
                        logger.error("Error waiting on req", ex);
                    }
                }

B:

synchronized (req) {
        while (!responseRecieved) {
            try {
                req.wait(3000);
            } catch (InterruptedException ex) {
                logger.error("Error waiting on req while trying to get state", ex);
            }
        }
    }

Thread A , Thread B . , .

0

All Articles