Re: wait finishes early?
mikew01 wrote:
I am trying to write a method that detects when a thread has timed out
waiting for a resource, for brevity I have included the important
parts below in the lock method.
I am finding that when I specify a value of around 6000ms and above
the period is calculated lower than the timeout which results in the
code thinking that the thread has not timed out waiting but has simply
been released from a notify.
It appears that either wait( timeout ) is releasing early or I am not
using the correct method for gauging the time to obtain period.
Any ideas?
Thanks
public void lock( Object requester, long timeout ) throws
InterruptedException
{
long start = System.currentTimeMillis();
synchronized ( requester )
{
requester.wait( timeout );
}
long period = System.currentTimeMillis() - start;
if ( period >= timeout )
{
System.out.println( "Timed out waiting for resource: " +
period );
}
}
It's possible you're getting spurious wakeups: Situations
where wait() returns for "no good reason." But these should
be fairly rare, and I've even seen it claimed that some JVM's
take steps to prevent them. So if you're getting a lot of
these premature wakeups, there's probably something else afoot.
A second possibility can be seen in the Javadoc: The waiting
thread will awaken "after the specified amount of real time has
elapsed, *more or less*" [emphasis mine]. This suggests that
the guarantees on the duration of the wait() may not be as
tight as you'd like.
Still another possibility is that something *is* actually
calling notify() or notifyAll(), or is interrupting the waiting
thread. What steps have you taken to rule this out?
Finally, the return from wait() does *not* mean that the
condition you're waiting for has come true, or even if it has
that it still holds. You should always be using wait() along
with some kind of test to see whether you should take action,
wait longer, or give up -- just the wait() alone isn't enough.
--
Eric Sosman
esosman@ieee-dot-org.invalid