If wait() throws an InterruptedException, does the thread wait until it acquires the object's monitor?

fhucho :

For example:

public synchronized Object get() {
    while (result == null) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
            // Do we own the monitor of this object?
        }
    }
    return result;
}

When e.printStackTrace() executes, are we guaranteed to own the object's monitor?

The reference says that when wait() returns after a notify() or notifyAll() call, the thread waits until it acquires the object's monitor. But what about the case when wait() throws an exception?

Nathan Hughes :

By the time wait returns (including the case where it throws InterruptedException) the thread has to have the monitor, otherwise it can't be executing in that synchronized method. The thread has to acquire the monitor before it can leave the wait method. Then once it's out of the wait method the thread has the monitor, and releases it when the thread leaves the method.

It's better here to throw the InterruptedException to the caller instead of eating it. Your goal here is to get out quickly and let the caller know an interruption happened so it can wrap things up. Eating it here also seems to mean you go back through the while loop again. Interruption is used by java.util.concurrent to implement cancellation, especially if you make use of java.util.concurrent tools it makes sense to write code that is compatible with them.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440111&siteId=1