InterruptedException and join
What you'll learn: How to properly handle the possibility of interruption when your thread is waiting for another thread to finish using join().
When you call join() to wait for another thread to complete, your waiting thread enters the WAITING (or TIMED_WAITING if you used a timeout) state. During this time, another thread might call interrupt() on your waiting thread. When this happens, join() immediately throws an InterruptedException and stops waiting.
Why This Matters
Just like with Thread.sleep(), join() is a blocking operation that declares throws InterruptedException. You must handle this checked exception. If your thread is interrupted while waiting in join(), you need to decide: Should you continue waiting? Should you propagate the interruption? Should you clean up and exit?
Handling the Exception
Thread worker = new Thread(() -> {
// Some long task
});
worker.start();
try {
worker.join(); // Wait for worker to finish
System.out.println("Worker completed successfully");
} catch (InterruptedException e) {
System.out.println("Interrupted while waiting for worker");
Thread.currentThread().interrupt(); // Restore interrupt status
}
When InterruptedException is caught, the interrupt status is cleared (just like with sleep()). Best practice is to restore it by calling Thread.currentThread().interrupt() so higher-level code knows interruption occurred.
Common Scenario
This pattern is crucial in shutdown logic: a main thread waits for worker threads to finish, but if the application needs to shut down immediately, it can interrupt the waiting thread rather than waiting indefinitely.
Key Takeaway: Always wrap join() in a try-catch block to handle InterruptedException. When caught, consider restoring the interrupt status so the interruption signal isn't lost.