Question:
What is the purpose of the Thread.interrupt()
method? I expect that if I call the interrupt()
method of a sleeping thread, anInterruptedException
will be thrown. Here is aquick code sample showing my thoughts (pleaseforgive the formatting):
I expect that when*/ class Timer extends Thread { public void run() { for(int i = 0; i < 20; i++) { try { sleep(100); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } } } public class Scheduler { public Scheduler() { timer_ = new Timer(); timer_.start(); } public void foo() { timer_.interrupt(); } private Timer timer_; public static void main(String args[]) { Scheduler s = new Scheduler(); s.foo(); } }/*
s.foo()
is called, Iwill see output resemblingWhat am I missing?Interrupted!
Answer:
I compiled and ran this code, and no message appeared. Thecurious behavior you’re experiencing can probably be attributed to the fact thatlike an Error
, an InterruptedException
isasynchronous. In otherwords, the InterruptedException
is thrown at a slightlydifferent pointduring the execution of _timer
each time it runs.
Asynchronous exceptions aren’t handled the same way as otherexceptions. The Java virtual machine must periodically check tosee if any asynchronous exceptions have been raised. This is usuallydone by special instructions inserted into your code by thecompiler. Naturally, this raises code optimization issues. Somecompilers only insert checks for asynchronous exceptions aftera “transfer of control.” This may mean a function call or acontext switch. It might even be the case that some compilers havean optimization option that doesn’t insert any checks for theseexceptions.