JVM之shutdown hook虚拟机关闭钩子分析

1:写在前面

jvm shutdown hook,即虚拟机关闭钩子,是允许在虚拟机退出前执行一些操作的机制,可以用于进行一些资源的清理等善后工作,对于包括但不限于以下的情况注册的虚拟机关闭钩子会被执行。

1:程序的正常退出
2:System.exit()
3:Ctrl+C
4:OutOfMemoryError
5:kill pid(注意非“-9”)

下面我们来测试下这些中的部分情况。

2:程序正常退出

2.1:测试代码

public class ShutdownHookTest {

    public void registerShutdownHook() {
        System.out.println("register shutdown hook begin...");
        // 注册停止运行钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("shut downhook run ...");
        }));
        System.out.println("register shutdown hook end...");
    }

    public static void main(String[] args) throws Exception {
        // 先注册停止运行钩子
        new ShutdownHookTest().registerShutdownHook();
        // 模拟正常的应用程序运行
        System.out.println("application running...");
        Thread.sleep(3000);
        System.out.println("application run over...");
    }
}

2.2:运行

register shutdown hook begin...
register shutdown hook end...
application running...
application run over...
shut downhook run ...

3:OutOfMemoryError

3.1:测试代码

public class ShutdownHookOutOfMemoryTest {

    public void registerOutOfMemoryShutdownHook() {
        System.out.println("register out of memory shut down hook begin...");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("out of memory shutdown hook run ...");
        }));
        System.out.println("register out of memory shut down hook end...");
    }

    public static void main(String[] args) throws Exception {
        // 注册虚拟机关闭钩子
        new ShutdownHookOutOfMemoryTest().registerOutOfMemoryShutdownHook();
        // 因为配置-Xmx20M,所以这里会发生OutOfMemoryError
        int FIFTY_M = 1024 * 1024 * 50;
        byte[] b = new byte[FIFTY_M];
        System.out.println("application running...");
        Thread.sleep(3000);
    }
}

3.2:运行

注意配置-Xmx20M:

register out of memory shut down hook begin...
register out of memory shut down hook end...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
out of memory shutdown hook run ...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值