如何在关闭挂钩中获取 return 代码

How to get return code in shutdown hook

我需要根据我的申请结果修改JVMreturn代码

但是显式调用 System.exit(代码) 是有风险的,因为应用程序很复杂并且很难识别 运行 线程的结束。

所以我想出了在 JVM 退出之前使用关闭钩子来修改 return 代码。

但是有一个问题,我怎样才能得到 JVM 的原始 return 代码,因为它可能是一个错误代码,而不是 0。

您不应该在关闭挂钩中调用退出方法,System.exit(status) 内部调用 Runtime.getRuntime().exit(status); 这将导致您的应用程序无限期阻塞。

根据 JavaDoc

If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely.

您无权访问 status,因为它可能会在调用所有关闭挂钩后发生变化。

由于关闭挂钩和退出状态不兼容,您可以创建一个 Throwable,其唯一功能是在 main 方法中被捕获。然后 catch 块成为您的关闭块。您可以在那里调用 System.exit(),如果需要,甚至可以保留您的关机代码。

class Emergency extends Throwable{
    int exit = 0;
}

public final class Entry {

    public static void main(String[] args){
            try {
                throw new Emergency();
            } catch (Emergency e) {
                // Shut down the app

            }
    }

}