Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Object.wait() method reacquire the monitor when it throws an exception?

The Java documentation I'm using makes it clear that the Object.wait() method reqcquires the associated monitor before it returns, regardless of whether it was notified or is a spurious wakeup; any normal method return will be preceeded by a monitor reacquisition.

However, it's a little less clear about what will happen in the event Object.wait() throws an exception, e.g., an Interrupted Exception. I'm inferring that it does indeed reacquire the lock before throwing an exception. However, the documentation isn't very explicit about it, so I'm not 100% sure...

Here is the documentaiton I'm looking at: http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28%29

So, is my inference correct, or does my calling code need to address the monitor state (e.g., reacquiring it if necessary) after an exception is thrown?

like image 221
Dave Lillethun Avatar asked Jul 08 '13 19:07

Dave Lillethun


People also ask

Does wait method throws exception?

An InterruptedException is thrown when a thread is interrupted while it's waiting, sleeping, or otherwise occupied. In other words, some code has called the interrupt() method on our thread.

What's the purpose of the object wait () method?

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). The current thread must own this object's monitor.

Does wait method throws an exception in Java?

When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread. InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification.

When wait () method is invoked?

Whenever the wait() method is called on an object, it causes the current thread to wait until another thread invokes the notify() or notifyAll() method for this object whereas wait(long timeout) causes the current thread to wait until either another thread invokes the notify() or notifyAll() methods for this object, or ...


1 Answers

The JLS specifies this in much more detail than Object#wait's Javadoc. According to that text, the lock must be unconditionally reacquired. Quoting the relevant bits:

  1. Thread t is added to the wait set of object m, and performs n unlock actions on m.

  2. Thread t does not execute any further instructions until it has been removed from m's wait set. The thread may be removed from the wait set due to any one of the following actions, and will resume sometime afterward:

    • [...]

    • An interrupt action being performed on t.

  3. Thread t performs n lock actions on m.

like image 58
Marko Topolnik Avatar answered Oct 14 '22 15:10

Marko Topolnik