Java – long timeout in the while loop?
I've read that you should put object in a Java loop Wait() call The reason is that this thread may be awakened, and the condition you wait for notification is still false (false wake)
Object. How about wait (long timeout)? Here, you don't want to recycle the condition because you want to time out after the specified time But if you don't put it in a loop, how do you make sure it won't wake up early?
Solution
This is a defect of Java IMO, although it may be a defect supported by the underlying threads in various operating system variables I suspect that Java knows if the wait times out, but the caller cannot retest the condition and specifically test the time ugly.
So you need to wait (long timeout) in a while loop and test to see if the timeout is exceeded I know there is no other way to do this
long timeoutExpiredMs = System.currentTimeMillis() + timeoutMs; while (!condition) { // we assume we are in a synchronized (object) here object.wait(timeoutExpiredMs - System.currentTimeMillis()); // we might get improperly awoken here so we need to see if we timed out if (System.currentTimeMillis() >= timeoutExpiredMs) { // we timed out break; } }