Dave Lillethun
Dave Lillethun

Reputation: 3118

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?

Upvotes: 6

Views: 226

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200236

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.

Upvotes: 5

Related Questions