Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.wait() exceeds timeout

Tags:

java

What could explain that the duration of Object.wait(timeout) exceeds the provided timeout value?

long start = System.currentTimeMillis();
obj.wait(1000);
long duration = System.currentTimeMillis() - start;
// sometimes (very rarely) duration may exceed 1500

Context: Somewhere in the depth of a very complex software there is a piece of code that makes such a wait and generates warning logs in case of excessive durations. In a production environment, with high traffic, some logs report huge overwaits (like 30 seconds). So I'm trying to reproduce it, understand what may happen and how to fix/improve it.

like image 639
sdabet Avatar asked Dec 04 '15 16:12

sdabet


People also ask

What does wait () do in Java?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

What class is wait () in Java?

The wait() method is defined in the Object class which is the super most class in Java. This method tells the calling thread (Current thread) to give up the lock and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll(). It is a final method, so we can't override it.

How do you wait on an object in Java?

wait() The wait() method causes the current thread to wait indefinitely until another thread either invokes notify() for this object or notifyAll().

Does sleep method accept timeout?

sleep method. Parameters: This method accepts a mandatory parameters timeout which is the minimum time to sleep. If this is less than or equal to zero, then do not sleep at all.


1 Answers

When a thread actually awakens after a time out expires or sleep wakes up is not exact. The doc for sleep has this note

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

notify is also subject to these variances.

So it has to do with the precision of the timers in the system and what other threads or processes are doing at the exact time the thread is eligible to run again. The general rule is a timeout like this is a minimum amount of time that will elapse. Object.notify has a variant that takes nanoseconds as well that gives you finer grain control over the amount of time that elapses.

see the Javadoc description about public final void wait(long timeout, int nanos)

like image 101
JJF Avatar answered Oct 08 '22 18:10

JJF