假设我们有一个用 java 编写的简单守护进程:
public class Hellow {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
while(true) {
// 1. do
// 2. some
// 3. important
// 4. job
// 5. sleep
}
}
}
我们使用它来守护它start-stop-daemon
默认情况下发送SIGTERM
(学期)信号开启--stop
假设当前执行的步骤是#2。此时此刻,我们正在发送 TERM 信号。
发生的情况是执行立即终止。
我发现我可以使用处理信号事件addShutdownHook()
但问题是它仍然中断当前执行并将控制权传递给处理程序:
public class Hellow {
private static boolean shutdownFlag = false;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
registerShutdownHook();
try {
doProcessing();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
static private void doProcessing() throws InterruptedException {
int i = 0;
while(shutdownFlag == false) {
i++;
System.out.println("i:" + i);
if(i == 5) {
System.out.println("i is 5");
System.exit(1); // for testing
}
System.out.println("Hello"); // It doesn't print after System.exit(1);
Thread.sleep(1000);
}
}
static public void setShutdownProcess() {
shutdownFlag = true;
}
private static void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Tralala");
Hellow.setShutdownProcess();
}
});
}
}
所以,我的问题是 - 是否有可能不中断当前的执行,而是处理TERM
在一个单独的线程(?)中发出信号,以便我能够设置shutdown_flag = True
这样循环main
有机会优雅地停下来吗?
我重写了registerShutdownHook()
方法,现在它按我想要的方式工作了。
private static void registerShutdownHook() {
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
System.out.println("Tralala");
Hellow.setShutdownProcess();
mainThread.join();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)