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

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


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.


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.


This doesn't exactly answer the question, but it will probably solve your problem: Use higher level concurrency mechanisms. Wait/notify is usually more low-level than you'd want, for this reason among many others.

For example, if you were using BlockingQueue.poll(long, TimeUnit), you could check if the result is null to know if you timed out.