Monday, September 13, 2010

Using Java SignalHandling and ShutDownHook

  • Singal Handling

Here I only briefly talk about the the Java Signal handling under Unix/Linux using Sun's implementation; In Sun's implementation, there is an interface SingleHandler and a Single class, they are located in rt.jar file,for every signal you want to capure, you need create a corresponding instance for it, and then register it into the Singal's handlers:

1. Singal signal = new Signal( TERM );

2. YourSignalHandler youHandler = new YourSignalHandler();

3. Singal.handle( singal, youHandler);

Then your handler is ready to handle signals, you may use kill -TERM processId to send signal to your signal handler.

When you use singal handling with JVM, you need consider some signals have already been listened by the JVM, and signals can only be handled by one handler, if you want to handle it, you must tell JVM to ignore it using -Xrs option when you bring up the JVM( Sun JVM)

  • Shudown hook

Sometime, you want to do some cleanup when your application is shuting down, for example, shutdown your thread pool, close your connection pool and close files gracefully.

1. Shutdown hook is a class which extends Thread class, and can be installed using Runtime.getRuntime().addShutdownHook() or removed using Runtime.getRuntime().removeShutdownHook()

2. Each shudown hook will be started when the JVM terminating, and they are running simultaneously, so synchronization should be considered if ncessary.

3. Shudown hook will be invoked under the following scenarios:

  • Application normal exits, for example, calling System.exit(0), Runtime.exit(), or the last non-deamon thread exits
  • JVM is terminated by some signals, such as SIGTERM, SIGHUP, etc.

4. Shutdown hook will not be invoked when:

  • JVM Crash
  • Runtime.halt() is called.
  • JVM -Xrs option is specified when bring up the JVM

In my previous post, I have talked about how to break the blocking I/O, especailly about how to gracefully shutdown the listener, now we know we could put the serverSocket.close() into a shudown hook, and then user sends a SIGTERM signal to the JVM, the JVM will be terminated and invoke the shudown hook to close the server socket. When the shutdown hook(s) are executed, the JVM will wait until all shutdown hooks finish their job, so you must make sure all of your shutdown hook finish their jobs properly, otherwise the JVM will hung.

For more detailed information about shutdown hook and signal handling, please refer to :

Revelations on Java signal handling and termination

 

Posted via email from Progress

No comments:

Post a Comment