Java 進程銷燬捕捉

package DestroyProcessTest;

/**
 * @Author: ZhangHao
 * @Description: 銷燬進程測試
 * @Date: 2020/6/6 11:12
 * @Version: 1.0
 */
public class DestroyProcessTest {
    public static void main(String[] args) throws InterruptedException {
        new DestroyProcessTest().exitTest();
    }

    private void activeExitTest() throws InterruptedException {
        // 程序正常結束時會觸發ShutdownHook
        Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
        Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
        Thread.sleep(3000);
    }

    private void outOfMemoryTest() throws InterruptedException {
        // -Xmx=20m
        // 堆內存超過設置的上限時,會觸發ShutdownHook
        Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
        Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
        Object[] objectArray = new Object[Integer.MAX_VALUE];
        for(int i = 0;i < objectArray.length;i++){
            objectArray[i] = new Object();
        }

        Thread.sleep(Long.MAX_VALUE);
    }

    private void exitTest() throws InterruptedException {
        // 手動關閉進程時不會觸發ShutdownHook
        Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
        Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
        Thread.sleep(Long.MAX_VALUE);
    }
}

java 遇到未知異常使程序崩潰,輸出jvm的dump崩潰信息到指定文件,然後殺死此進程:https://blog.csdn.net/m0_37518406/article/details/78900393

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章