A thread that is notified and interrupted while waiting

JLS 17.2.4:

If the flow notified and interrupted while waiting, it can either:

[...]

Could you provide an example of a thread that is interrupted and notified while waiting? I don't understand how this is possible, because when we call

Thred.interrupt()

      

or

obj.notify()

      

the thread will be removed from the wait set. As the further call does not apply to the waiting thread. It has not yet been removed from the pending set.

+3


source to share


2 answers


Consider this code:

synchronized(obj) {
   obj.notify();
   threadWatingOnObj.interrupt();
}

      



Before the thread executing the above code releases the lock, none of the notified threads can continue. Therefore, when control returns to such a thread from its call obj.wait()

, it will be notified and aborted.

+4


source


It looks like a question from an exam. You have to fill in the gap, right?

I think this question is poorly thought out because "interrupted" is a state that a thread can be in, and "awaiting" is a state that a thread can be in, but "notification" is not a state.

If a thread calls wait()

when it is already in an interrupted state, calling wait () will return an exception. Likewise, if the thread is in a waiting state when it is interrupted, calling wait () will also return an exception in that case.



Perhaps when they say "a thread is notified and terminated" they mean that the thread was waiting and it was notified and then the interrupt was delivered while the thread was still in the wait () call, trying to reset the mutex.

I have no internal knowledge of what is going on in this case, but based on the Javadoc for, Object.wait()

I expect the wait () call to return ok after it acquires the mutex.

0


source







All Articles