Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 20, 1997

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, an InterruptedException will be thrown. Here is a quick code sample showing my thoughts (please forgive 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, I will see output resembling
Interrupted! 
What am I missing?

Answer:
I compiled and ran this code, and no message appeared. The curious behavior you're experiencing can probably be attributed to the fact that like an Error, an InterruptedException is asynchronous. In other words, the InterruptedException is thrown at a slightly different point during the execution of _timer each time it runs.

Asynchronous exceptions aren't handled the same way as other exceptions. The Java virtual machine must periodically check to see if any asynchronous exceptions have been raised. This is usually done by special instructions inserted into your code by the compiler. Naturally, this raises code optimization issues. Some compilers only insert checks for asynchronous exceptions after a "transfer of control." This may mean a function call or a context switch. It might even be the case that some compilers have an optimization option that doesn't insert any checks for these exceptions.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date