Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   2. Concurrency  >   2.7. Graceful shutdown

2.7. Graceful shutdown
Last updated: 31 January 2013.

This tutorial explains how to make a thread shut down gracefully.

When they are used to implement servers (like TCP or UDP servers), threads perform certain operations repeatedly in an infinite loop like this:

public void run(){
   
while(true){
         
// perform operations
          //...
          //...
   
}
}

Consequently, the only way to terminate such a thread is to hit Ctrl-c if you are running the thread from a command prompt or hit the Terminate button if you are using an IDE like Eclipse or, if the thread was started by some UNIX script, by killing the corresponding process with the command kill -9 PID where PID is the ID of the process. By doing so, you may lose data if your program was writing data to a file or database. For this reason, it is recommended to make threads terminate gracefully by writing explicit tests in the method run in order to control the thread's life as shown below:

public void run(){
   
while(! isInterrupted()){
         
// perform operations
          //...
          //...

         
if(goOn == false)
               
break;
   
}
}

In the above sample, the thread can be terminated in two ways: On the one hand, goOn is a variable of type boolean (declared outside the method run) that can be set to false by another thread, which makes the current thread exit the loop and die. On the other hand, if another thread calls the method interrupt, the current thread also exits the loop at the next iteration since isInterrupted returns true.

Of course, only one test is enough. Depending on your program, you can choose to test either the interrupted status of the thread or the boolean goOn.


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   2. Concurrency  >   2.7. Graceful shutdown
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7