Friday, April 27, 2012

Java: Release resources on program termination

Applications use different resources (database connections, file descriptors, etc.) that need to be released when program terminates.

Java application can register a ShutdownHook that would be executed before the last non-daemon process is terminated. It also works when application is terminated by System.exit() or external interrupt request (kill).

Java Runtime has a method addShutdownHook that registers a Thread that would be started to do the cleaning up.

Example, closing database connection on shutdown:

// register shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
      DatabaseFactory.shutdown();
   }
});

N.B.: ShutdownHook may not be executed if VM crashes.


No comments:

Post a Comment