Reputation: 4093
Here is a case where a thread is waiting for notify() or a timeout. Here a while loop is added to handle spurious wake up.
boolean dosleep = true;
while (dosleep){
try {
wait(2000);
/**
* Write some code here so that
* if it is spurious wakeup, go back and sleep.
* or if it is timeout, get out of the loop.
*/
} catch (InterruptedException e) {
e.printStackTrace();
}
}
In this case how can I distinguish between a spurious wake up and time out? If it is a spurious wake up, i need to go back and wait. And if it is a timeout, i need to get out of the loop.
I can easily identify the case of notify(), because i will be setting the dosleep variable to false while notify() call.
EDIT: i am using 1.4 java version, due to embedded project requirement. I cannot use Condition
as it is available only post 1.5.
Thanks in advance.
Upvotes: 12
Views: 3026
Reputation: 54406
You could do this:
boolean dosleep = true;
long endTime = System.currentTimeMillis() + 2000;
while (dosleep) {
try {
long sleepTime = endTime - System.currentTimeMillis();
if (sleepTime <= 0) {
dosleep = false;
} else {
wait(sleepTime);
}
} catch ...
}
That should work fine in Java 1.4, and it will ensure that your thread sleeps for at least 2000ms.
Upvotes: 9
Reputation:
You need to keep track of your timeout if you want to distinguish the two cases.
long timeout = 2000;
long timeoutExpires = System.currentTimeMillis() + timeout;
while(dosleep) {
wait(timeout);
if(System.currentTimeMillis() >= timeoutExpires) {
// Get out of loop
break;
}
}
That said, denis's recommendation of using the Condition
class is the better way to do this.
Upvotes: 6
Reputation: 11775
I believe Lock
s and Condition
will better fit your need in this case. Please check the javadocs for Condition.awaitUntil()
- it has an example of usage
Upvotes: 5