Runtime中 shutdown hook的用法

来源:互联网 发布:行知教育 昂立哪个好 编辑:程序博客网 时间:2024/05/20 05:25

根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象。在Runtime 注册后,如果 jvm 要停止前,这些 shutdown hook 便开始执行。声明:Runtime.addShutdownHook(Thread t)

举例如下:

  1. package john2;
  2.  
  3. /**
  4.  * test shutdown hook
  5.  * All rights released and correctness not guaranteed.
  6.  */
  7. public class ShutdownHook implements Runnable {
  8.     
  9.     public ShutdownHook() {
  10.         // register a shutdown hook for this class.
  11.         // a shutdown hook is an initialzed but not started thread, which will get up and run
  12.         // when the JVM is about to exit. this is used for short clean up tasks.
  13.         Runtime.getRuntime().addShutdownHook(new Thread(this));
  14.         System.out.println(">>> shutdown hook registered");
  15.     }
  16.     
  17.     // this method will be executed of course, since it's a Runnable.
  18.     // tasks should not be light and short, accessing database is alright though.
  19.     public void run() {
  20.         System.out.println("/n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
  21.         this.cleanUp();
  22.         System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");
  23.     }
  24.     
  25.         // (-: a very simple task to execute
  26.     private void cleanUp() {
  27.         for(int i=0; i < 7; i++) {
  28.             System.out.println(i);
  29.         }
  30.     }
  31.  
  32.     /**
  33.      * there're couple of cases that JVM will exit, according to the Java api doc.
  34.      * typically:
  35.      * 1. method called: System.exit(int)
  36.      * 2. ctrl-C pressed on the console.
  37.      * 3. the last non-daemon thread exits.
  38.      * 4. user logoff or system shutdown.
  39.      * @param args
  40.      */
  41.     public static void main(String[] args) {
  42.         
  43.         new ShutdownHook();
  44.         
  45.         System.out.println(">>> Sleeping for 5 seconds, try ctrl-C now if you like.");
  46.         
  47.         try {
  48.             Thread.sleep(5000);     // (-: give u the time to try ctrl-C
  49.         } catch (InterruptedException ie) { 
  50.             ie.printStackTrace(); 
  51.         }
  52.         
  53.         System.out.println(">>> Slept for 10 seconds and the main thread exited.");
  54.     }
  55.  
  56. }
  57.  



参考资料:
1. Java API Documentation
2. http://java.sun.com/j2se/1.3/docs/guide/lang/hook-design.html

也许有人会担心性能问题,shutdown hook会不会占用太多的VM的资源,答案是shutdown hook不会占用VM太多的资源,因为shutdown hook 只是一个已初始化但尚未启动的线程。这意味着它只在程序关闭的时候才会启动,而不是在程序一开始运行时就启动。而在大多数的Java平台中,如果一个线程没有启动(即没有调用线程的start()函数)VM不会分配资源给线程。因此维护一群没有启动的线程不会给VM带来太大的负担.

最后还要注意以下两点:
1.如果VM crash,那么不能保证关闭挂钩(shutdown hooks)能运行.试想一下如果Windows XP突然蓝屏了那么本来计划在关机之前的更新也就无法进行了.
2.如果调用Runtime.halt()方法来结束程序的话,那么关闭挂钩(shutdown hooks)也不会执行

原创粉丝点击