Sunday, March 18, 2012

Kill a thread in Java

Dear reader, 

The topic of discussion of this article is:
    How can I kill a thread? 
    And that too without using stop() method which is a deprecated one?

After reading lot of articles I found that there are two ways we can achieve this:
1) Make a boolean flag variable which will say a thread to run or not and change the property later,
   the complete program I have written which is tested in my system.

2) By making use of Thread.interrupt() method which is more standard and I prefer to use that. However
   Thread.interrupt() doesn't stop the thread execution immediately. Interruption is a cooperative mechanism.  
   When one thread interrupts another, the interrupted thread does not necessarily stop what it is doing 
   immediately. Instead, interruption is a way of politely asking another thread to stop what it is doing 
   if it wants to, at its convenience. Again the complete program I have given.   
   
========Program 1=========
class Outer {    
    public static boolean flag = true;
    Outer() {
        new Test().start();
    } 
    class Test extends Thread { 
        public void run() {
            while(Outer.flag) {
                System.out.println("Thread is running");
            }  
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Outer out=new Outer();      //Thread is running till 1000 milliseconds.
        Thread.sleep(1000);
        out.flag=false;             //Changing the boolean value, now thread will stop execution.
    }
}
//Output:
Thread is running
Thread is running
Thread is running
......
......
Thread is running
Thread is running
Now thread is stopped


========Program 2=========
public class RunningThread implements Runnable {
    long start = System.currentTimeMillis();

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                System.out.println("Thread is running..");
                Thread.sleep(10);
            } 
            catch (InterruptedException ex) {
                System.out.println("RunningThread got Interrupted");
                System.out.println("Running time in millis: "+ (System.currentTimeMillis() - start));
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String[] args) {
        RunningThread rt = new RunningThread();
        Thread t = new Thread(rt);
        //Set the current main thread to sleep 2000 milli seconds and then stop the RunnableThread
        System.out.println("Starting a thread..");
        t.start();
        try {
            Thread.sleep(2000);
            t.interrupt();
        } 
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
//Output:
Thread is running..
Thread is running..
Thread is running..
......
......
Thread is running..
Thread is running..
Thread is running..
RunningThread got Interrupted
Running time in millis: 2000

==========================Some theoritical contents=======================
More details about Interruption: below theory taken from IBM site:

Blocking methods :
When a method throws InterruptedException, it is telling you several things in addition to the fact 
that it can throw a particular checked exception. It is telling you that it is a blocking method and 
that it will make an attempt to unblock and return early -- if you ask nicely.

A blocking method is different from an ordinary method that just takes a long time to run. The completion 
of an ordinary method is dependent only on how much work you've asked it to do and whether adequate 
omputing resources (CPU cycles and memory) are available. The completion of a blocking method, on the 
other hand, is also dependent on some external event, such as timer expiration, I/O completion, or the 
action of another thread (releasing a lock, setting a flag, or placing a task on a work queue). Ordinary 
methods complete as soon as their work can be done, but blocking methods are less predictable because they 
depend on external events. Blocking methods can compromise responsiveness because it can be hard to predict 
when they will complete.

Because blocking methods can potentially take forever if the event they are waiting for never occurs, it 
is often useful for blocking operations to be cancelable. (It is often useful for long-running non-blocking 
methods to be cancelable as well.) A cancelable operation is one that can be externally moved to completion 
in advance of when it would ordinarily complete on its own. The interruption mechanism provided by Thread 
and supported by Thread.sleep() and Object.wait() is a cancellation mechanism; it allows one thread to request 
that another thread stop what it is doing early. When a method throws InterruptedException, it is telling you 
that if the thread executing the method is interrupted, it will make an attempt to stop what it is doing and 
return early and indicate its early return by throwing InterruptedException. Well-behaved blocking library 
methods should be responsive to interruption and throw InterruptedException so they can be used within 
cancelable activities without compromising responsiveness.

Thread interruption:
Every thread has a Boolean property associated with it that represents its interrupted status. The interrupted 
status is initially false; when a thread is interrupted by some other thread through a call to Thread.interrupt(), 
one of two things happens. If that thread is executing a low-level interruptible blocking method like Thread.sleep(), 
Thread.join(), or Object.wait(), it unblocks and throws InterruptedException. Otherwise, interrupt() merely sets the 
thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see 
if it has been requested to stop what it is doing; the interrupted status can be read with Thread.isInterrupted() 
and can be read and cleared in a single operation with the poorly named Thread.interrupted().

Interruption is a cooperative mechanism. When one thread interrupts another, the interrupted thread does not necessarily 
stop what it is doing immediately. Instead, interruption is a way of politely asking another thread to stop what it is 
doing if it wants to, at its convenience. Some methods, like Thread.sleep(), take this request seriously, but methods 
are not required to pay attention to interruption. Methods that do not block but that still may take a long time to 
execute can respect requests for interruption by polling the interrupted status and return early if interrupted. You 
are free to ignore an interruption request, but doing so may compromise responsiveness.

One of the benefits of the cooperative nature of interruption is that it provides more flexibility for safely constructing 
cancelable activities. We rarely want an activity to stop immediately; program data structures could be left in an 
nconsistent state if the activity were canceled mid-update. Interruption allows a cancelable activity to clean up any
work in progress, restore invariants, notify other activities of the cancellation, and then terminate. 
-------------------------------END---------------------------

No comments:

Post a Comment