devxlogo

What is the Thread.interrupt()method’s purpose?

What is the Thread.interrupt()method’s purpose?

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):

*/   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();      }   }/*
I expect that when s.foo() is called, Iwill see output resembling
Interrupted! 
What am I missing?

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist