Ravisha
Ravisha

Reputation: 3353

Object.wait(0) waits forever

I have below piece of code, where the wait time is calculated elsewhere.
In some of the situations the wait time value is 0. What I notice is that when the wait time is zero the thread seem to wait forever. I could not find anything specific to this case in the Javadoc. I could just add a check for this, but I just need to understand why this is happening and is it allowed to pass 0 wait time

synchronized (monitor) {
    try {
        monitor.wait(wait); // <-- sometime 0
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Upvotes: 1

Views: 5413

Answers (3)

Janitha
Janitha

Reputation: 79

Object.wait(0);

will simply make it wait forever. So you can embed your code inside an if condition,

if(wait>0)
{
//your code
}

Upvotes: 1

Thilo
Thilo

Reputation: 262834

The Javadocs say:

If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

So specifying wait(0) means wait indefinitely.

Upvotes: 17

FThompson
FThompson

Reputation: 28707

From the Javadocs:

If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

If your goal is to avoid waiting when your wait value is zero, you can add a condition:

if (wait > 0) {
    synchronized (monitor) {
        try {
            monitor.wait(wait);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 6

Related Questions