下面简单演示一下如何使用Shutdown Hook机制关闭数据库连接。 publicclassDataBaseConnectMain{privatestaticConnectionconn;publicstaticvoidmain(String[]args){System.out.println("The main thread starts executing");// 初始化数据库连接initConnection();System.out.println("Do some data querying and processing");...
ShutdownHook的数据结构与执行顺序 当我们添加一个ShutdownHook时,会调用ApplicationShutdownHooks.add(hook),往ApplicationShutdownHooks类下的静态变量private static IdentityHashMap<Thread, Thread> hooks添加一个hook,hook本身是一个thread对象 ApplicationShutdownHooks类初始化时会把hooks添加到Shutdown的hooks中去,而...
当我们添加一个ShutdownHook时,会调用ApplicationShutdownHooks.add(hook),往ApplicationShutdownHooks类下的静态变量private static IdentityHashMap<Thread, Thread> hooks添加一个hook,hook本身是一个thread对象 ApplicationShutdownHooks类初始化时会把hooks添加到Shutdown的hooks中去,而Shutdown的hooks是系统级的Shutdown...
static{try{Shutdown.add(1/* shutdown hook invocation order */,false/* not registered if shutdown in progress */,newRunnable(){publicvoidrun(){runHooks();}});hooks=newIdentityHashMap<>();}catch(IllegalStateExceptione){// application shutdown hooks cannot be added if// shutdown is in pro...
//创建关闭钩子 就是线程28 ShutdownHook shutdownHook =newShutdownHook();29//像虚拟机中注册关闭钩子30 Runtime.getRuntime().addShutdownHook(shutdownHook); 然后,应用程序会等待用户输入 System.in.read(); 当用户按Enter键时,应用程序退出,但是虚拟机会执行关闭钩子,效果是输出字符串“Shutting down”。
简介:Shutdown hook是Jvm关闭的钩子,是通过Runtime#addShutdownHook(Thread hook)方法来实现的,根据api是注解可知它就是一系例的已初始化但尚未执行的线程对象。我们可以通过向Jvm注册一个钩子,实现在程序退出时关闭资源、平滑退出的功能。所谓的优雅停机也可以这么搞。
上面代码中“Runtime.getRuntime().addShutdownHook”方法就是添加了一个ShutdownHook。这个方法的参数是一个Thread对象,在程序退出时就会执行这个Thread对象了。想看看上面这个例子的执行结果吗?执行结果如上,这是在程序正常运行完成结束时,就会执行Runtime.getRuntime().addShutdownHook方法添加的Thread的内容了。
ShutdownHook原理 ShutdownHook的数据结构与执行顺序 当我们添加一个ShutdownHook时,会调用ApplicationShutdownHooks.add(hook),往ApplicationShutdownHooks类下的静态变量private static IdentityHashMap ApplicationShutdownHooks类初始化时会把hooks添加到Shutdown的hooks中去,而Shutdown的hooks是系统级的ShutdownHook,并且系...
ApplicationShutdownHooks位于下标1处,且应用级的hooks,执行时调用的是thread类的start方法,所以应用级的ShutdownHook是异步执行的,但会等所有hook执行完毕才会退出。 static void runHooks() { Collectionthreads; synchronized(ApplicationShutdownHooks.class) { ...
removeShutdownHook(java.lang.Thread), halt(int), exit(int) 首先来测试第一种,程序正常退出的情况: packagecom.hook; importjava.util.concurrent.TimeUnit; publicclassHookTest { publicvoidstart() { Runtime.getRuntime().addShutdownHook(newThread(newRunnable() { ...