Reputation: 612
The below wait()
call is always throwing InterruptedException. It is not that some other thread is interrupting it. There is no delay between the call and the exception being thrown. I have put logs to check the time lapse between the call and the catch of exception.
Also, Thread.sleep(long)
yields the same result.
public synchronized void retryConnection()
{
// . .. some code
try
{
wait();
}
catch(InterruptedException e)
{
log(Level.SEVERE, "InterruptedException " , e);
}
// . .. some code
}
I have tried these random things:
call this method in a new thread. Then it works fine. It is a waiting and notification mechanism also works.
put the same code again, that is, wait again after the exception is caught. Then it is properly waiting.
Observation: When the call is coming from a netty(server) thread, it fails but if it is coming from some other java thread, it works. So my question is: Is there any mechanism or thread state where wait()
or Thread.sleep()
is forbidden and throws an exception if they are invoked?
I have checked the interrupted flag and it is 'false' always.
Upvotes: 3
Views: 7292
Reputation: 7620
InterruptedException
is a perfectly normal event to occur when using Object.wait()
, and thread.sleep()
coupled with Object.notify()
, and Object.notifyAll()
.
This is called Inter-thread Communication.
A thread which owns the object's monitor, can call Object.wait()
- a call which causes this current thread to lose the ownership of the monitor and to wait / block until another thread owning said object's monitor will call Object.notify()
or Object.notifyAll()
.
This means that active thread owning the lock awakes other thread(s) from waiting (or sleeping, or blocking) state. This originating thread has to also relinquish its grasp on objects lock, before the thread(s) that got notified can proceed.
The thread which is waiting on a lock receives the notification as InterruptedException
. It then can proceed as by the time it has received the exception, it has been given the ownership of the lock.
Please see Java Thread lifecycle diagram to for more information.
So in your case:
InterruptedException
is not a failure.notify()
or notifyAll()
and the exception is never thrownObject.wait()
and Thread.sleep()
you get the following (from javaDoc):
The interrupted status of the current thread is cleared when this exception is thrown.
Upvotes: 2