根据JavaAPI,所谓shutdownhook就是已经初始化但尚未开始执行的线程对象。在Runtime注册后,如果jvm要停止前,这些shutdownhook便开始执行。声明:Runtime.addShutdownHook(Thread t)
举例如下:
- packagejohn2;
- /**
- *testshutdownhook
- *Allrightsreleasedandcorrectnessnotguaranteed.
- */
- publicclassShutdownHookimplementsRunnable{
- publicShutdownHook(){
- //registerashutdownhookforthisclass.
- //ashutdownhookisaninitialzedbutnotstartedthread,whichwillgetupandrun
- //whentheJVMisabouttoexit.thisisusedforshortcleanuptasks.
- Runtime.getRuntime().addShutdownHook(newThread(this));
- System.out.println(">>>shutdownhookregistered");
- }
- //thismethodwillbeexecutedofcourse,sinceit'saRunnable.
- //tasksshouldnotbelightandshort,accessingdatabaseisalrightthough.
- publicvoidrun(){
- System.out.println("/n>>>Abouttoexecute:"+ShutdownHook.class.getName()+".run()tocleanupbeforeJVMexits.");
- this.cleanUp();
- System.out.println(">>>Finishedexecution:"+ShutdownHook.class.getName()+".run()");
- }
- //(-:averysimpletasktoexecute
- privatevoidcleanUp(){
- for(inti=0;i<7;i++){
- System.out.println(i);
- }
- }
- /**
- *there'recoupleofcasesthatJVMwillexit,accordingtotheJavaapidoc.
- *typically:
- *1.methodcalled:System.exit(int)
- *2.ctrl-Cpressedontheconsole.
- *3.thelastnon-daemonthreadexits.
- *4.userlogofforsystemshutdown.
- *@paramargs
- */
- publicstaticvoidmain(String[]args){
- newShutdownHook();
- System.out.println(">>>Sleepingfor5seconds,tryctrl-Cnowifyoulike.");
- try{
- Thread.sleep(5000);//(-:giveuthetimetotryctrl-C
- }catch(InterruptedExceptionie){
- ie.printStackTrace();
- }
- System.out.println(">>>Sleptfor10secondsandthemainthreadexited.");
- }
- }
参考资料:
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)也不会执行