如何在Java中正常处理SIGTERM信号?

Isl*_*aev 6 java daemon process sigterm start-stop-daemon

假设我们有一个用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
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我们将其守护进程start-stop-daemon默认情况下使用以下命令发送SIGTERM(TERM)信号:--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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是-是否可以不中断当前执行,而是TERM在单独的线程(?)中处理信号,以便我可以进行设置,shutdown_flag = True以便使循环main有机会优雅地停止?

Isl*_*aev 5

我重写了该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);
            }

        }
    });  
}
Run Code Online (Sandbox Code Playgroud)