On the previous page, we looked at the basics of thread interruption in Java. On this page, we'll explore a few more details that we need to consider.
In the above example, you may be thinking, "what if the call to interrupt() happens while the other thread is printing the message (rather than in the Thread.sleep() call)?". Well, it turns out not to matter in this case. If the interruptee is not in a blocking method, then:
So provided that the interrupted thread periodically calls a blocking call such as Thread.sleep(), the interruption mechanism still works.
What if the interrupted method isn't ever (or soon) going to call a blocking method like like sleep() or wait()? In this case:
To manually check for the interrupted flag, we call isInterrupted(). For example:
public void performLongCalculation() throws InterruptedException { for (int i = 0; i < PART_COUNT; i++) { if (isInterrupted()) throw new InterruptedException(); performPartOfCalculation(); } }
This technique is usually more useful when the thread is performing a combination of interruptible and non-interruptible calls. Otherwise, we can implement our own cancellation flag (typically via a volatile boolean).
A common piece of bad program design is to "micro-manage" InterruptedException (and indeed, exceptions in general), by catching it and "pretending nothing happened". But in a good design, like any exception, it should be dealt with cleanly. What exactly to do with InterruptedException can depend on the program and situation, of course, but as a rule of thumb:
An InterruptedException should cause the overall task to be cancelled.
This generally means:
public class MyRunnable implements Runnable() { BlockingQueuependingStrings; public void run() { try { while (true) { String str = pendingStrings.take(); ... } } catch (InterruptedException iex) { Thread.currentThread().interrupt(); } } }
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.