Java shutdown hook are handy to run some code when program exit. We can use java.lang.Runtime.addShutdownHook(Thread t) method to add a shutdown hook in the JVM.

程序退出时,使用Java shutdown钩子可以方便地运行一些代码。 我们可以使用java.lang.Runtime.addShutdownHook(Thread t)方法在JVM中添加一个关闭钩子。

Java关闭挂钩 (Java shutdown hook)

Java shutdown hook runs in these two cases.

在这两种情况下,将运行Java shutdown挂钩。

  1. The program exits normally, or we call System.exit() method to terminate the program. Read more about Java System Class.该程序正常退出,或者我们调用System.exit()方法终止该程序。 阅读有关Java System Class的更多信息。
  2. User interrupts such as Ctrl+C, system shutdown etc.用户中断,例如Ctrl + C,系统关闭等。

Important points about Java Shutdown Hook are;

有关Java Shutdown Hook的要点是:

  1. We can add multiple shutdown hooks using Runtime addShutdownHook() method.我们可以使用Runtime addShutdownHook()方法添加多个关闭挂钩。
  2. Shutdown hooks are initialized but not-started threads. They start when JVM shutdown triggers.关机挂钩是已初始化但未启动的线程 。 它们在JVM关闭触发时启动。
  3. We can’t determine the order in which shutdown hooks will execute, just like multiple threads executions.我们无法确定关闭挂钩的执行顺序,就像执行多个线程一样。
  4. All un-invoked finalizers are executed if finalization-on-exit has been enabled.如果启用了退出时终结,则将执行所有未调用的终结器。
  5. There is no guarantee that shutdown hooks will execute, such as system crash, kill command etc. So you should use it only for critical scenarios such as making sure critical resources are released etc.无法保证关机钩子会执行,例如系统崩溃,kill命令等。因此,应仅将其用于紧急情况下,例如确保释放关键资源等。
  6. You can remove a hook using Runtime.getRuntime().removeShutdownHook(hook) method.您可以使用Runtime.getRuntime().removeShutdownHook(hook)方法删除钩子。
  7. Once shutdown hooks are started, it’s not possible to remove them. You will get IllegalStateException.启动关闭挂钩后,将无法删除它们。 您将获得IllegalStateException
  8. You will get SecurityException if security manager is present and it denies RuntimePermission("shutdownHooks").如果存在安全管理器并且拒绝RuntimePermission("shutdownHooks")则将获得SecurityException。

Java关闭挂钩示例 (Java shutdown hook example)

So let’s see example of shutdown hook in java. Here is a simple program where I am reading a file line by line from some directory and processing it. I am having program state saved in a static variable so that shutdown hook can access it.

因此,让我们来看一下Java中的shutdown hook的示例。 这是一个简单的程序,其中我从某个目录中逐行读取文件并进行处理。 我将程序状态保存在静态变量中,以便关机挂钩可以访问它。

package com.journaldev.shutdownhook;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;public class FilesProcessor {public static String status = "STOPPED";public static String fileName = "";public static void main(String[] args) {String directory = "/Users/pankaj/temp";Runtime.getRuntime().addShutdownHook(new ProcessorHook());File dir = new File(directory);File[] txtFiles = dir.listFiles(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {if (name.endsWith(".txt"))return true;elsereturn false;}});for (File file : txtFiles) {System.out.println(file.getName());BufferedReader reader = null;status = "STARTED";fileName = file.getName();try {FileReader fr = new FileReader(file);reader = new BufferedReader(fr);String line;line = reader.readLine();while (line != null) {System.out.println(line);Thread.sleep(1000); // assuming it takes 1 second to process each record// read next lineline = reader.readLine();}status = "PROCESSED";} catch (IOException | InterruptedException e) {status = "ERROR";e.printStackTrace();}finally{try {reader.close();} catch (IOException e) {e.printStackTrace();}}}status="FINISHED";}}

Most important part of above code is line no 16 where we are adding the shutdown hook, below is the implementation class.

上面代码中最重要的部分是第16行,我们在其中添加了shutdown钩子,下面是实现类。

package com.journaldev.shutdownhook;public class ProcessorHook extends Thread {@Overridepublic void run(){System.out.println("Status="+FilesProcessor.status);System.out.println("FileName="+FilesProcessor.fileName);if(!FilesProcessor.status.equals("FINISHED")){System.out.println("Seems some error, sending alert");}}
}

It’s a very simple use, I am just logging state when the shutdown hook started and if it was not finished already, then send an alert (Not actually, its just logging here).

这是一种非常简单的用法,我只是在记录关闭挂钩开始时的状态,如果还没有完成,则发送警报(实际上不是在这里记录它)。

Let’s see some program execution through terminal.

让我们看看通过终端执行一些程序。

  1. Program terminated using Ctrl+C command.

    As you can see in the above image, shutdown hook started executing as soon as we tried to kill the JVM using Ctrl+C command.

    如上图所示,当我们尝试使用Ctrl + C命令杀死JVM时,shutdown挂钩就开始执行。

  2. Program executed normally.

    Notice that hook is called in case of normal exit too, and it’s printing status as finished.

    请注意,如果在正常退出的情况下也调用了钩子,则其打印状态为完成。

  3. Kill Command to terminate JVM.

    I used two terminal windows to fire kill command to the java program, so operating system terminated the JVM and in this case shutdown hook was not executed.

    我使用了两个终端窗口向Java程序发射kill命令,因此操作系统终止了JVM,在这种情况下,未执行关闭钩子。

That’s all for shutdown hook in java, I hope you learned about JVM shutdown hooks and might find a use for it.

这就是Java中的关闭钩子,我希望您了解了JVM关闭钩子,并可能会找到用处。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/9113/java-shutdown-hook-runtime-addshutdownhook

Java关闭挂钩– Runtime.addShutdownHook()相关推荐

  1. Tomcat的带有守护程序和关闭挂钩的正常关闭

    我的最后两个博客讨论了长时间轮询和Spring的DeferredResult技术,并且为了展示这些概念,我将我的Producer Consumer项目中的代码添加到了Web应用程序中. 尽管该代码演示 ...

  2. java 关闭另一个jvm_JVM安全退出(如何优雅的关闭java服务)

    背景 用户:货都到了,购物车里怎么还有刚买的东西,what? 产品:有用户反映,提单完成了,怎么没清购物车,研发赶紧看看是不是有bug啊? 研发:恩,我看看,!@#¥%--&*()一顿狂查,搜 ...

  3. java关闭applet_java – Applet会自动关闭

    我的 java应用程序发生了非常奇怪的事情.总之,问题是它有时会在30-60秒的工作后自行关闭. 具体情况如下: >该应用程序实际上是在applet设置中启动的,applet加载主应用程序jar ...

  4. 聊聊Java中的Runtime类

    概述 Runtime类封装了运行时的环境.每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接. 我们不能实例化一个Runtime对象,应用程序也不能创建自己的 ...

  5. Java中的Runtime类详解

    Java中的Runtime类详解 1.类注释 /**Every Java application has a single instance of class Runtime that allows ...

  6. java关闭窗口函数_2016年将是Java终于拥有窗口函数的那一年!

    java关闭窗口函数 你没听错. 到目前为止,出色的窗口功能是SQL独有的功能. 甚至复杂的函数式编程语言似乎仍然缺少这种漂亮的功能(如果我错了,请纠正我,Haskell伙计们). 我们撰写了许多有关 ...

  7. bat java 启动脚本_从bat脚本运行的Java应用程序上的Windows关闭挂钩

    小编典典 在极少数情况下,虚拟机可能会中止,即在不完全关闭的情况下停止运行.当虚拟机在外部终止时会发生这种情况,例如在Unix上使用SIGKILL信号或在Microsoft Windows上使用Ter ...

  8. java关闭事件_为Java程序添加退出事件

    package org.swing.os; import java.util.*; import java.io.*; /** * 为Java程序添加退出事件 * * @author wuhq */ ...

  9. java 关闭阻塞线程池_如果优雅地关闭ExecutorService提供的java线程池

    每一个线程都会占用系统资源,因此线程池的关闭与清理同样重要,本文介绍我们如何优雅地关闭线程池. 一. ExecutorService中关闭线程池的方法 1. shutdown() 停止接收新任务,原来 ...

最新文章

  1. 【PAT (Advanced Level) Practice】1113 Integer Set Partition (25 分)
  2. golang goroutine实现_golang技术随笔(二)理解goroutine
  3. Android之用AccessibilityService实现红包插件
  4. 如何使用Apache的Prediction IO Machine Learning Server构建推荐引擎
  5. QT中QWidget、QDialog及QMainWindow的区别
  6. Illustrator 教程,如何在 Illustrator 中创建单线徽章?
  7. 35.伪造请求超时的ICMP数据包
  8. 64位计算机很慢,win7 64位旗舰版电脑网速太慢怎么解决
  9. 酒桌上的潜规则和技巧,男人必学
  10. 大麦网抢票软件工具开发系列(一)
  11. 【转】cidaemon.exe进程CPU占用率高怎么办?
  12. 手机APP如何访问局域网服务器
  13. 用pe修改计算机ip地址,实现WinPE上网功能修改IP及DNS方法
  14. 非托管内存转换为System.Drawing.Bitmap
  15. 人人网登录并写留言板(Requests,js逆向)
  16. 新浪微博Android客户端开发之OAuth认证篇
  17. IDEA的maven的package打包
  18. Sql 中两个数除法计算结果等于0原因是什么?
  19. 分享两个“整人”的脚本语言代码
  20. 太空建站、探测火星、发射次数“50+”——2021中国航天这些大事值得铭记

热门文章

  1. 初探Bootstrap
  2. [Unity菜鸟] Character控制移动
  3. [转载] Python reversed函数及用法【小白学习Python必备知识】
  4. [转载] sklearn FutureWarning: numpy not_equal will not check..., The comparison did not return the sam
  5. 【Python】@staticmethod和@classmethod的作用与区别
  6. 字节数组byte[]和整型,浮点型数据的转换——Java代码
  7. django-celery beat报错 error pid
  8. 浅谈数据结构之顺序队列(五)
  9. 专技天下河北省2016年专业技术人员继续教育公需科目题库答案(答题器)
  10. 【Java】函数使用