Does calling Thread.interrupt() before a Thread.join() cause the join() to throw an InterruptedException immediately?

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · May 17, 2012 · Viewed 15.4k times · Source

Basically, what the question title says.

Thread t = new Thread(someRunnable);
t.start();
t.interrupt();
t.join(); //does an InterruptedException get thrown immediately here?

From my own tests, it seems to, but just wanted to be sure. I'm guessing Thread.join() checks the interrupted status of the thread before doing its "wait" routine?

Answer

Gray picture Gray · May 17, 2012

Does calling Thread.interrupt() before a Thread.join() cause the join() to throw an InterruptedException immediately?

No it will not throw. Only if the current thread that is calling the join() method gets interrupted will join() throw InterruptedException. t.interrupt() is interrupting the thread you just started, while t.join() will only throw InterruptedException if the thread that is doing the join-ing (maybe the main thread?) is itself interrupted.

 Thread t = new Thread(someRunnable);
 t.start();
 t.interrupt();
 t.join();  // will _not_ throw unless this thread calling join gets interrupted

Also it is important to realize that interrupting a thread does not cancel it and join() is not like a Future in that it will return the exception the thread threw.

When you interrupt a thread, any calls the thread is making to sleep(), wait(), join(), and other interruptible methods will throw InterruptedException. If those methods are not called then the thread will continue running. If a thread does throw a InterruptedException in response to being interrupted and then quits, that exception will be lost unless you you used t.setDefaultUncaughtExceptionHandler(handler).

In your case, if the thread is interrupted and finishes because it returns, then the join will finish -- it will not throw an exception. Common thread code to handle an interrupt properly is as follows:

 public void run() {
    try {
       Thread.sleep(10000);
    } catch (InterruptedException e) {
       // a good pattern is to re-interrupt the thread when you catch
       Thread.currentThread().interrupt();
       // another good pattern is to make sure that if you _are_ interrupted,
       // that you stop the thread
       return;
    }
 }