RSS Feed for This PostCurrent Article

Do a graceful shutdown of your Java Application when Ctr-C, Kill…

Download Source Code

When I am developing Java application for backend processes to do ETL, I often need to ensure that resources are properly cleaned up when the application is shutdown. However, user behavior is quite unpredictable. In either Windows or Unix, process can be terminated by force by the user, by sending the kill signal.

In Java, in order to do graceful shutdown, I normally add a shutdown hook to the Java runtime, using the Runtime.getRunTime().addShutdownHook method.

As an example, I have an interface for my application which has the start and shutdown method

public interface IApp {

void start();

void shutDown();
}

I wrote a ShutdownInterceptor class which extends the Thread class.

public class ShutdownInterceptor extends Thread {

private IApp app;

public ShutdownInterceptor(IApp app) {
this.app = app;
}

public void run() {
System.out.println(“Call the shutdown routine”);
app.shutDown();
}
}

My sample application will implement the IApp interface. Have a look at the main method.

public class SampleApp extends BaseApp implements IApp {

public void start() {
try {
System.out.println(“Sleeping for 5 seconds before shutting down”);
Thread.sleep(5000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

public void shutDown() {
// Do a graceful shutdown here
System.out.println(“Shutdown is called”);
}

public static void main(String args[]) {
IApp app = new SampleApp();
ShutdownInterceptor shutdownInterceptor = new ShutdownInterceptor(app);
Runtime.getRuntime().addShutdownHook(shutdownInterceptor);
app.start();
}
}

At startup, I created the SampleApp class, and then the ShutdownInterceptor class with the application instance. Then I add the interceptor to the Java runtime.

The application sleeps for 5 seconds. When it exits, ShutdownInterceptor will call application shutdown method automatically.


Trackback URL


RSS Feed for This Post4 Comment(s)

  1. Lincoln | Jan 7, 2009 | Reply

    Clear, concise and helpful.

    Many thanks.

  2. WW | Jun 5, 2009 | Reply

    But this doesn’t work if the user hits CTRL-C

  3. Dragon | May 8, 2010 | Reply

    So useful information!

  4. CliftonSRhoe | Jun 11, 2016 | Reply

    Hi there, i read your blog every once in awhile and
    i own an identical one and so i was only curious when you get a great deal of spam comments?
    If how do you prevent it, any plugin or what you can recommend?
    I recieve a lot lately it’s driving me mad so any support is very much appreciated.

3 Trackback(s)

  1. From Add Multithreading Function to Java Application using ExecutorService | twit88.com | Sep 28, 2007
  2. From Java - Signal Handling | twit88.com | Feb 6, 2008
  3. From Java: Understanding System.exit | Programming Resources | Aug 20, 2008

RSS Feed for This PostPost a Comment

*