java關閉當前窗口,Java關閉掛鉤– Runtime.addShutdownHook()

 2023-11-19 阅读 19 评论 0

摘要: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

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關閉當前窗口,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如何徹底關閉更新、 有關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";}}

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.

讓我們看看通過終端執行一些程序。

  1. Program terminated using Ctrl+C command.

    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掛鉤就開始執行。

  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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/183035.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息