时间:2021-05-19
根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象。在Runtime 注册后,如果 jvm 要停止前,这些 shutdown hook 便开始执行。声明:Runtime.addShutdownHook(Thread t)
举例如下:
复制代码 代码如下:
package john2;
/**
* test shutdown hook
* All rights released and correctness not guaranteed.
*/
public class ShutdownHook implements Runnable {
public ShutdownHook() {
// register a shutdown hook for this class.
// a shutdown hook is an initialzed but not started thread, which will get up and run
// when the JVM is about to exit. this is used for short clean up tasks.
Runtime.getRuntime().addShutdownHook(new Thread(this));
System.out.println(">>> shutdown hook registered");
}
// this method will be executed of course, since it's a Runnable.
// tasks should not be light and short, accessing database is alright though.
public void run() {
System.out.println("/n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
this.cleanUp();
System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");
}
// (-: a very simple task to execute
private void cleanUp() {
for(int i=0; i < 7; i++) {
System.out.println(i);
}
}
/**
* there're couple of cases that JVM will exit, according to the Java api doc.
* typically:
* 1. method called: System.exit(int)
* 2. ctrl-C pressed on the console.
* 3. the last non-daemon thread exits.
* 4. user logoff or system shutdown.
* @param args
*/
public static void main(String[] args) {
new ShutdownHook();
System.out.println(">>> Sleeping for 5 seconds, try ctrl-C now if you like.");
try {
Thread.sleep(5000); // (-: give u the time to try ctrl-C
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(">>> Slept for 10 seconds and the main thread exited.");
}
}
也许有人会担心性能问题,shutdown hook会不会占用太多的VM的资源,答案是shutdown hook不会占用VM太多的资源,因为shutdown hook 只是一个已初始化但尚未启动的线程。这意味着它只在程序关闭的时候才会启动,而不是在程序一开始运行时就启动。而在大多数的Java平台中,如果一个线程没有启动(即没有调用线程的start()函数)VM不会分配资源给线程。因此维护一群没有启动的线程不会给VM带来太大的负担.
最后还要注意以下两点:
如果VM crash,那么不能保证关闭挂钩(shutdown hooks)能运行.试想一下如果Windows XP突然蓝屏了那么本来计划在关机之前的更新也就无法进行了.
如果调用Runtime.halt()方法来结束程序的话,那么关闭挂钩(shutdown hooks)也不会执行
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
详解Linux中的关机和重启命令一shutdown命令shutdown[选项]时间选项:?123-c:取消前一次关机命令-h:关机-r:重启二shutdown实
前言最近由于公司的项目开发,就学习了在react关于hook的使用,对其有个基本的认识以及如何在项目中去应用hook。在这篇博客中主要从以下的几个点进行介绍:h
IOS中runtime使用方法整理做iOS的朋友都知道或听说runtime,这个东西很像java的反射机制,但功能远胜于java的反射。通过runtime我们可
Androidjson数据解析详解移动开发经常要与服务器数据交互,也常使用json数据格式,那就说说Androidjson解析。1.最简单json格式解析如下:
Scala解析Json字符串的实例详解1.添加相应依赖Json解析工具使用的json-smart,曾经对比过Java的fastjson、gson。Scala的j