JAVA 虛擬機鉤子

Shutdown Hook

Java程序常常也會遇到進程掛掉的狀況,一些狀態沒有正確的保存下來,這時候就須要在JVM關掉的時候執行一些清理現場的代碼。JAVA中的ShutdownHook提供了比較好的方案。java

JDK提供了Java.Runtime.addShutdownHook(Thread hook)方法,能夠註冊一個JVM關閉的鉤子,這個鉤子能夠在一下幾種場景中被調用:ide

  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)

來測試第一種,程序正常退出的狀況:spa

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();  
        }  
    }  
}

運行結果:code

The Application is doing something  blog

Execute Hook.....進程

相關文章
相關標籤/搜索