美文网首页
Java.Runtime.addShutdownHook(Thr

Java.Runtime.addShutdownHook(Thr

作者: raincoffee | 来源:发表于2018-04-12 11:12 被阅读51次

    Runtime.addShutdownHook理解

    转载:https://blog.csdn.net/u013256816/article/details/50394923

    Java程序经常也会遇到进程挂掉的情况,一些状态没有正确的保存下来,这时候就需要在JVM关掉的时候执行一些清理现场的代码。JAVA中的ShutdownHook提供了比较好的方案。

    JDK提供了Java.Runtime.addShutdownHook(Thread hook)方法,可以注册一个JVM关闭的钩子,这个钩子可以在一下几种场景中被调用:

    1. 程序正常退出
    2. 使用System.exit()
    3. 终端使用Ctrl+C触发的中断
    4. 系统关闭
    5. OutOfMemory宕机
    6. 使用Kill pid命令干掉进程(注:在使用kill -9 pid时,是不会被调用的)

    下面是JDK1.7中关于钩子的定义:

        public void addShutdownHook(Thread hook)
    参数:
        hook - An initialized but unstarted Thread object 
    抛出: 
        IllegalArgumentException - If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run 
        IllegalStateException - If the virtual machine is already in the process of shutting down 
        SecurityException - If a security manager is present and it denies RuntimePermission("shutdownHooks")
    从以下版本开始: 
        1.3 
    另请参见:
        removeShutdownHook(java.lang.Thread), halt(int), exit(int)
    

    其他解释,大体上含义一样的。

    该方法用来在jvm中增加一个关闭的钩子。当程序正常退出,系统调用 System.exit方法或虚拟机被关闭时才会执行添加的shutdownHook线程。其中shutdownHook是一个已初始化但并不有启动的线程,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作。  
    

    测试

    首先来测试第一种,程序正常退出的情况:

    package com.hook;
    
    import java.util.concurrent.TimeUnit;
    
    public class HookTest
    {
        public void start()
        {
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run()
                {
                    System.out.println("Execute Hook.....");
                }
            }));
        }
        
        public static void main(String[] args)
        {
            new HookTest().start();
            System.out.println("The Application is doing something");
            
            try
            {
                TimeUnit.MILLISECONDS.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    结果:
    The Application is doing something  
    Execute Hook.....
    

    下面再来测试第五种情况

    package com.hook;
    
    import java.util.concurrent.TimeUnit;
    
    public class HookTest2
    {
        public void start()
        {
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run()
                {
                    System.out.println("Execute Hook.....");
                }
            }));
        }
        
        public static void main(String[] args)
        {
            new HookTest().start();
            System.out.println("The Application is doing something");
            byte[] b = new byte[500*1024*1024];
            try
            {
                TimeUnit.MILLISECONDS.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    
    }
    
    运行参数设置为:-Xmx20M  这样可以保证会有OutOfMemoryError的发生。
    结果:
    The Application is doing something  
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space  
        at com.hook.HookTest2.main(HookTest2.java:22)  
    Execute Hook..... 
    

    相关文章

      网友评论

          本文标题:Java.Runtime.addShutdownHook(Thr

          本文链接:https://www.haomeiwen.com/subject/rgrxkftx.html