Friday, May 27, 2011

Application Shutdown Hook

JavaImage via Wikipedia
I was working with an application that needed to be run as a daemon. When the application is shutdown, we needed to do it in a clean manner, and release resources. So the question becomes how is it done.

Fortunately, the Runtime class provides mechanism for adding a shutdown hook. The shutdown hook code below was added to the constructor. The shutdown method is invoked when the application is shutdown, for example CTRL+C.

// add shutdown hook to stop server
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                shutdown();
            }
        });
    }

public void shutdown() {
// add code to cleanly shutdown service here.
}
Enhanced by Zemanta

0 comments :

Popular Posts