Friday, June 17, 2011

Chapter 5: Stopping a Thread

When you want a thread to terminate or stop based on some condition, you have several approaches available. For ex, you may want to terminate a thread because it has completed the intended operation or because the user clicked the exit button. Though there are many approaches to do it, we are going to take a look at the two most common ways of doing it.

1. Setting a Flag

The most common way of stopping a thread is to set some internal flag to signal that the thread should stop. The thread can then periodically query that flag to determine if it should exit.
Lets look at a sample code that follows this approach

...
public class Test extends Thread {
...
private volatile boolean done = false;
...
public void run( ) {
while (!done) {
...
}
}
public void setDone( ) {
done = true;
}
}


Here we've created the boolean flag done to signal the thread that it should quit. Now instead of looping forever, the run() method examines the state of that variable on every loop and returns when the done flag has been set. That terminates the thread.
The important point to note here is that, this boolean variable must be set appropriately by some part of your code otherwise you will be stuck with a thread that doesn't know when to stop.

For example, we can add this logic of modifying this boolean variable when the user clicks on the “Exit” button.

Trivia:
This raises an interesting question: is it better to create a new thread like this, or would it be better somehow to suspend the existing thread and resume it when we're ready? Of course, we don't yet have the tools necessary to program the suspension and resumption of the thread, so that's the reason we've done it this way. It would be more natural simply to suspend and resume the thread. Don't worry just yet. We will cover that very soon.

2. Interrupting a Thread

The previous method of setting a flag has a simple drawback. Lets say you have a method that updates this boolean flag. But, if you thread started the loop iteration before the flag was updated, it will have to finish the iteration and then it will check the boolean flag during the next iteration.

This may sound to be not too dangerous but imagine this:

Lets say, inside your loop, you are going to wait for user input through the command prompt. Since the user clicked Exit, he thinks the program is over whereas the program is waiting for him to type something. The user isn’t going to input anything and your thread isn’t going to die because they are both stuck.

Now do you understand why the previous method wasn't the best possible way to stop a thread?
When you arrange for a thread to terminate, you often want it to complete its blocking method immediately: you don't want to wait for the data (or whatever be the case) anymore because the thread is going to exit anyway. You can use the interrupt() method of the Thread class to interrupt any blocking method.

The interrupt() method has two effects. First, it causes any blocked method to throw an InterruptedException.

The second effect is to set a flag inside the thread object that indicates the thread has been interrupted. To query this flag, use the isInterrupted() method. That method returns true if the thread has been interrupted.

Here's how a thread uses this information to determine whether or not it should terminate:

public class TestAgain extends Thread {
...

public void run( ) {
while (!isInterrupted( )) {
...
}
}
}


This example is almost exactly the same as the one in which we use a done flag to signal that the thread should return. In this case, we use the interrupted flag instead. That means we no longer need the setDone() method. Instead of calling the setDone() method, the actionPerformed( ) method associated with the Exit button in our application now does this:

producer.interrupt( );

So, when the main thread executes this statement while our thread is sleeping, it gets the interrupted exception and immediately returns from the run() method.
Otherwise, when our thread goes for the next iteration of the loop, it sees that the interrupted flag has been set and returns from its run() method. Either ways, our thread completes its task and terminates.

Note that this technique does not completely eliminate the possibility of indefinite wait that we saw with the set flag technique but is better that technique. Such a situation is called a race condition and we shall be covering it in depth in future and learn how to program in such a way that our threads perform optimally.

Previous: Thread Lifecycle

Next: Determining the Current Thread

3 comments:

  1. Another way to kill a thread is by nullifying it.
    e.g.
    Thread t = new MyThread();
    t.start();
    ..
    ...
    //On some condition
    t = null;

    In the earlier version of Java, Thread class had a method stop() which is deprecated in later versions.

    - Pankaj

    ReplyDelete
  2. I am unable ot understand this. Java api explanation says - "If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException" ---------- here wt is meant by clearing the status? And also what i undesrstood is that thread should not interrupted while sleeping/waiting/join, thats why if its interrupted, exception is thrown. Am I missing something? or totally wrong? Please explain..

    ReplyDelete
  3. Good post Anand. By the way here is mine way of Stopping Thread in Java let me know how do you find it.

    ReplyDelete

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers