Search code examples
javamultithreadingconcurrencywait

Thread interrupt: will it cancel oncoming wait() call?


I have a thread which has an incoming job queue (a LinkedList containing job descriptions). The thread blocks with wait() on the queue when there's no job to work on. An external job dispatcher object awakes it with notify() when it places new jobs on the queue.

At shutdown of my program i call interrupt() on the Thread. This raises InterruptedException when the Thread awaits for jobs in wait(). My question is: what will happen if i interrupt the Thread while it's not blocking but doing some kind of work, the processed item was the last in the queue (so queue is now empty) and execution pasts the isInterrupted() check before the interrupted flag is set so it calls wait() again? Will it throw an InterruptedException because the interrupted flag has already been set or the thread waits forever because new jobs will never arrive to the queue and there's no one to interrupt the wait?


Solution

  • yes, your interrupted thread will throw an InterruptedException upon calling wait(). this is pretty simple to test for yourself.

    public class TestInt {
        public static void main(String[] args) throws Exception
        {
            Thread.currentThread().interrupt();
    
            synchronized(TestInt.class) {
                TestInt.class.wait();
            }    
        }    
    }
    

    also, note the javaodc for Object.wait():

    InterruptedException - if any 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.