UPDATED: Now, to get things clear, the situation is: there is a project which is started only by calling the main() function in A class, and in the main() a shutdown hook is added. The A starts many other worker threads and they keep running until the ShutdownHook is executed. My question is how to let the shutdown hook be executed? We used to use kill -9 PID to kill the process. And I am not sure will the shutdown hook be executed with directly kill. I searched a lot, most say with kill -9 the proper shutdown will be ignored? But my colleague said we have been using this way to stop the service for long time...I am now totally confused.
public class A {
//...omitted unrelevant
public static void main(String[] args) {
final A ctrl = new A(configName, routerId);
ctrl.startup();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
if (logger.isWarnEnabled()) {
logger.warn("Kill signal received, starting shutdown...");
}
ctrl.shutdown(); //calling the real shutdown
if (logger.isWarnEnabled()) {
logger.warn("Shutdown done, going down.");
}
Set<Thread> threadSet=Thread.getAllStackTraces().keySet();
String currentThreadName = Thread.currentThread().getName();
for (Thread thread : threadSet) {
if (logger.isWarnEnabled()) {
logger.warn("Killing : " + thread.getName() + " " + thread.getClass().getName());
}
if (!thread.getName().equals(currentThreadName)) {
thread.stop();
}
}
System.exit(0);
}
}
}
// ...
public void shutdown() {
if (logger.isDebugEnabled()) {
logger.debug("requesting shutdown");
}
for (Worker w : worker) {
w.requestShutdown();
}
for (Thread t : workerThreads) {
try {
t.join();
} catch (InterruptedException e) {
}
}
if (logger.isDebugEnabled()) {
logger.debug("shutdown finished");
}
}}
Use SIGINT signal, as suggested by kiheru. That is what is sent when you press Ctrl+C.
http://en.wikipedia.org/wiki/Unix_signal