Thread interrupt is not always working!

 

Background
Interrupting a thread means stopping what it is doing before it has completed its task, effectively aborting its current operation. Whether the thread dies, waits for new tasks, or goes on to the next step depends on the application.

Although it may seem simple at first, you must take some precautions in order to achieve the desired result. There are some caveats you must be aware of as well.

First of all, forget the Thread.stop method. Although it indeed stops a running thread, the method is unsafe and was deprecated, which means it may not be available in future versions of the Java.

Another method that can be confusing for the unadvised is Thread.interrupt. Despite what its name may imply, the method does not interrupt a running thread (more on this later), as below example demonstrates. It creates a thread and tries to stop it using Thread.interrupt. The calls toThread.sleep() give plenty of time for the thread initialization and termination. The thread itself does not do anything useful.

class Example1 extends Thread {
  public static void main( String args[] ) throws Exception {
    Example1 thread = new Example1();
   System.out.println( "Starting thread..." );
   thread.start();
   Thread.sleep( 3000 );
   System.out.println( "Interrupting thread..." );
   thread.interrupt();
   Thread.sleep( 3000 );
   System.out.println( "Stopping application..." );
   System.exit( 0 );
  }
 
  public void run() {
    while ( true ) {
     System.out.println( "Thread is running..." );
      long time = System.currentTimeMillis();
      while ( System.currentTimeMillis()-time < 1000 ) {
      }
    }
  }
}

If you run the code above, you should see something like this on your console:
Starting thread…
Thread is running…
Thread is running…
Thread is running…
Interrupting thread…
Thread is running…
Thread is running…
Thread is running…
Stopping application…
Thread is running…
Thread is running…
Thread is running…
………………………….
Even after Thread.interrupt() is called, the thread continues to run for a while.

As demonstrated above, the method Thread.interrupt() does not interrupt a running thread. What the method actually does is to throw an interrupt if the thread is blocked, so that it exits the blocked state. More precisely, if the thread is blocked at one of the methods Object.wait,Thread.join, or Thread.sleep, it receives an InterruptedException, thus terminating the blocking method prematurely.

interrupt() is not meant to stop a Thread in normal circumstances, and if you interrupt()a thread, in most cases it’ll just go on doing its stuff. In 99.9% of cases, it is just bad design to stop a thread with interrupt().

 

The best, recommended way to interrupt a thread is to use a shared variable to signal that it must stop what it is doing. The thread must check the variable periodically, especially during lengthy operations, and terminate its task in an orderly manner.

class Example3 extends Thread {
  volatile boolean stop = false;
 
  public static void main( String args[] ) throws Exception {
   Example3 thread = new Example3();
   System.out.println( "Starting thread..." );
   thread.start();
   Thread.sleep( 3000 );
   System.out.println( "Asking thread to stop..." );
   thread.stop = true;
   thread.interrupt();
   Thread.sleep( 3000 );
   System.out.println( "Stopping application..." );
   System.exit( 0 );
  }
 
  public void run() {
    while ( !stop ) {
     System.out.println( "Thread running..." );
      try {
      Thread.sleep( 1000 );
      } catch ( InterruptedException e ) {
      System.out.println( "Thread interrupted..." );
      }
    }
   System.out.println( "Thread exiting under request..." );
  }
}

Although this method requires some coding, it is not difficult to implement and give the thread the opportunity to do any cleanup needed, which is an absolute requirement for any multithreaded application. Just be sure to declare the shared variable as volatile or enclose any access to it into synchronized blocks/methods.

FROM HERE

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s