`
huobengluantiao8
  • 浏览: 1030796 次
文章分类
社区版块
存档分类
最新评论

Runtime中 shutdown hook的用法

 
阅读更多

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

举例如下:

  1. packagejohn2;
  2. /**
  3. *testshutdownhook
  4. *Allrightsreleasedandcorrectnessnotguaranteed.
  5. */
  6. publicclassShutdownHookimplementsRunnable{
  7. publicShutdownHook(){
  8. //registerashutdownhookforthisclass.
  9. //ashutdownhookisaninitialzedbutnotstartedthread,whichwillgetupandrun
  10. //whentheJVMisabouttoexit.thisisusedforshortcleanuptasks.
  11. Runtime.getRuntime().addShutdownHook(newThread(this));
  12. System.out.println(">>>shutdownhookregistered");
  13. }
  14. //thismethodwillbeexecutedofcourse,sinceit'saRunnable.
  15. //tasksshouldnotbelightandshort,accessingdatabaseisalrightthough.
  16. publicvoidrun(){
  17. System.out.println("/n>>>Abouttoexecute:"+ShutdownHook.class.getName()+".run()tocleanupbeforeJVMexits.");
  18. this.cleanUp();
  19. System.out.println(">>>Finishedexecution:"+ShutdownHook.class.getName()+".run()");
  20. }
  21. //(-:averysimpletasktoexecute
  22. privatevoidcleanUp(){
  23. for(inti=0;i<7;i++){
  24. System.out.println(i);
  25. }
  26. }
  27. /**
  28. *there'recoupleofcasesthatJVMwillexit,accordingtotheJavaapidoc.
  29. *typically:
  30. *1.methodcalled:System.exit(int)
  31. *2.ctrl-Cpressedontheconsole.
  32. *3.thelastnon-daemonthreadexits.
  33. *4.userlogofforsystemshutdown.
  34. *@paramargs
  35. */
  36. publicstaticvoidmain(String[]args){
  37. newShutdownHook();
  38. System.out.println(">>>Sleepingfor5seconds,tryctrl-Cnowifyoulike.");
  39. try{
  40. Thread.sleep(5000);//(-:giveuthetimetotryctrl-C
  41. }catch(InterruptedExceptionie){
  42. ie.printStackTrace();
  43. }
  44. System.out.println(">>>Sleptfor10secondsandthemainthreadexited.");
  45. }
  46. }



参考资料:
1.JavaAPIDocumentation
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)也不会执行

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics