Search code examples
javamultithreadingwaitsynchronizednotify

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


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
            }

Solution

  • You can't differentiate between the two unless you provide some additional code. For example by adding a ThreadLocal Boolean that is set to true only on notify()

    But first you must make sure your logic requires this differentiation.