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 runs in these two cases.
在這兩種情況下,將運行Java shutdown掛鉤。
System.exit()
method to terminate the program. Read more about Java System Class. 該程序正常退出,或者我們調用System.exit()
方法終止該程序。 閱讀有關Java System Class的更多信息。 Important points about Java Shutdown Hook are;
java如何徹底關閉更新、 有關Java Shutdown Hook的要點是:
addShutdownHook()
method. 我們可以使用Runtime addShutdownHook()
方法添加多個關閉掛鉤。 Runtime.getRuntime().removeShutdownHook(hook)
method. 您可以使用Runtime.getRuntime().removeShutdownHook(hook)
方法刪除鉤子。 IllegalStateException
. 啟動關閉掛鉤后,將無法刪除它們。 您將獲得IllegalStateException
。 RuntimePermission("shutdownHooks")
. 如果存在安全管理器并且拒絕RuntimePermission("shutdownHooks")
則將獲得SecurityException。 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";}}
Java退出程序、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).
js拖拽交換位置, 這是一種非常簡單的用法,我只是在記錄關閉掛鉤開始時的狀態,如果還沒有完成,則發送警報(實際上不是在這里記錄它)。
Let’s see some program execution through terminal.
讓我們看看通過終端執行一些程序。
java callable接口和runnable,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掛鉤就開始執行。
Notice that hook is called in case of normal exit too, and it’s printing status as finished.
請注意,如果在正常退出的情況下也調用了鉤子,則其打印狀態為完成。
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
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态