当关机挂钩坏了

IAm*_*aja 9 java runtime shutdown

如果我在我的Java程序的运行时添加一个关闭钩子,如下所示:

public class MyShutdownHook implements Runnable
{
    @Override
    public void run()
    {
        // Stuff I want executed anytime
        // the program, Java, or the OS exits normally,
        // crashes, or terminates unexpectedly for any reason.
    }
}

// The in another method...
Runtime.getRuntime().addShutdownHook(new MyShutdownHook());
Run Code Online (Sandbox Code Playgroud)

......那么有没有曾经在那里,任何情况下,run()方法将不会执行该程序/ Java的/ OS退出时正常,崩溃或意外终止?如果是这样,什么情况下能够绕过Runtime关闭钩子,为什么?

小智 6

  • 如果进程被终止,则不会执行关闭挂钩.

  • 如果进程崩溃,则不会执行关闭挂钩.

  • 如果您有Windows服务并且关闭钩子需要很长时间才能执行,它将被终止.

  • 如果向进程发送了SIGTERM信号(UNIX中的常规"kill"命令),则将运行shutdown hook.如果发送SIGKILL(kill -9),它将无法运行. (2认同)