简体   繁体   中英

wait() is always throwing InterruptedException

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.

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:

  • Receiving InterruptedException is not a failure.
  • Netty trying to be performant, does not let threads wait too long, hence you keep getting the notifications.
  • When you run your threads, you don't call notify() or notifyAll() and the exception is never thrown
  • For both Object.wait() and Thread.sleep() you get the following (from javaDoc):

    The interrupted status of the current thread is cleared when this exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM