How to differentiate when wait(long timeout) exit for notify or timeout?

Hernán Eche picture Hernán Eche · Aug 3, 2010 · Viewed 30.7k times · Source

Having this wait declaration:

public final native void wait(long timeout) throws InterruptedException;

It could exit by InterruptedException, or by timeout, or because Notify/NotifyAll method was called in another thread, Exception is easy to catch but...

There is any way to know if the exits cause was timeout or notify?

EDIT:

This is a tricky way that could work, (although I don't like it)

          long tBefore=System.currentTimeMillis();
          wait(TIMEOUT);
          if ((System.currentTimeMillis() - tBefore) > TIMEOUT) 
            { 
               //timeout
            }

Answer

Darron picture Darron · Aug 3, 2010

There is one more reason that notify can return: spurious wakeup. This is an unlikely but possible thing, because preventing spurious wakeups is very expensive on some hardware/OS combinations.

Because of this you always have to call wait() in a loop and re-check the condition that you are waiting for. During this work it's easy to check for timeout at the same time.

For details I recommend the book "Java Concurrency In Practice". And using higher level constructs that will get this all correct for you.