我正在尝试设置一个关闭钩子来处理SIGTERM(kill -15)。它关闭但看起来并没有优雅地完成**处理**功能,因为它从不输出日志“线程已关闭”。
public class Runner {
public static void main(String[] args) {
Test test = new Test();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
logger.warn("Shutting things down..."); // This works
test.stop();
} catch (Exception ex) {
logger.error("Error shutting the app gracefully", ex);
}
}
});
test.processing();
}
}
public class Test {
private volatile boolean processingExit = false;
public void stop() {
processingExit = true;
}
public void processing() {
while (!processingExit) {
//do work here
logger.info("doing work... keep printing..."); //This works until I send a kill -15 signal
}
// This log never works
logger.info("Thread has been shutdown"); // This doesn't works
}
}
答案 0 :(得分:0)
问题是,一旦关闭钩子线程完成,进程就会暂停,你需要让关闭钩子线程等待主线程。
从https://stackoverflow.com/a/2922031/1544715
复制来自the docs:
当虚拟机开始其关闭序列时,它将以某种未指定的顺序启动所有已注册的关闭挂钩,并让它们同时运行。 当所有挂钩都完成后,如果启用了finalization-on-exit,它将运行所有未读取的终结器。最后,虚拟机将停止。