Liam Fledgings Liam Fledgings - 4 months ago 14
Java Question

Java wait() not Throwing InterruptedException

I have an object on thread A that is calling

wait()
while another object on thread B does some work then calls thread A's object's
notify()
. Thread A then performs some post-processing.

My problem is pretty straightforward:

synchronized(this)
{
while(!flag)
{
try
{
wait();
getLogger().info("No longer waiting");
}
catch (InterruptedException ie)
{
getLogger().info("Wait threw InterruptedException");
}
}
}


Results in an info message of "No longer waiting" instead of "Wait threw InterruptedException".

I am confused, because of this (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait()):


Throws:

InterruptedException - if another thread interrupted the
current thread before or while the current thread was waiting for a
notification. The interrupted status of the current thread is cleared
when this exception is thrown.


Why am I getting odd behavior?

Thanks.

Answer

When a thread waits using wait(), he actually waits for notify(). So once notify() has been called by the other thread, this thread will continue, if you will call interrupt(), you would get the exception.

Also, from the documents you linked to:

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object

notify releases the thread from the lock.

InterruptedException - if another thread interrupted the current thread before or while the current thread was waiting for a notification.