Java ShutdownHook无法正常运行

如何解决Java ShutdownHook无法正常运行

我想要做的是在while(true)循环中运行一些代码,然后当我按下IntelliJ或控件c中的终止按钮时,第二段代码运行干净地终止并保存了我所有的进度到一个文件。目前,我的程序正在使用在我的主要方法中运行的以下代码运行:

File terminate = new File(terminatePath);
while(!terminate.canRead()) {
    // process
}
// exit code

但是,为了终止代码,我必须在“ terminatePath”目录中创建一个文件,并且当我想再次开始运行时,必须删除该文件。这是很草率和烦人的事情,所以我想学习正确的方法来做这样的事情。我在网上找到的大多数情况都说使用关闭钩子,并在下面提供此代码:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { 
        // exit code
    }
});

然后我将while循环直接放在主要方法中的该钩子下面:

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() { 
           // exit code
        }
    });
    while (true) {
    // process
    }
}

但是在这段代码中,关闭钩子似乎并不是最后运行的东西。终止后,退出代码将立即运行,然后还会执行while循环的更多迭代。

我假设我错误地应用了退出挂钩,但是我似乎无法在线找到正确的方法。我可以更改此代码以使while循环在运行出口挂钩之前可靠地停止吗?谢谢。

解决方法

Windows用户的序言:通常在Windows 10上,我从 IntelliJ IDEA Eclipse Git Bash运行Java程序。它们都不会触发Ctrl-C上的任何JVM关闭钩子,可能是因为它们以比常规Windows终端 cmd.exe 更少协作的方式杀死进程。因此,为了测试整个场景,我确实必须从 cmd.exe PowerShell 运行Java。

更新:在 IntelliJ IDEA 中,您可以单击“退出”按钮,就像从左到右的箭头指向一个空的正方形-而不是“停止”按钮,就像一个实心的正方形一样在典型的音频/视频播放器上。另请参阅herehere


请查看Javadoc for Runtime.addShutdownHook(Thread)。它说明了shutdown钩子只是一个初始化但未启动的线程,它将在JVM关闭时启动。它还指出,您应该以线程安全的方式进行防御性编码,因为不能保证所有其他线程都已被中止。

让我向您展示这种效果。不幸的是,由于不幸的是您没有提供MCVE,因为什么代码片段都不起作用来重现您的问题并不是特别有帮助,所以我创建了一个代码片段来解释您的情况似乎正在发生什么:

public class Result {
  private long value = 0;

  public long getValue() {
    return value;
  }

  public void setValue(long value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return "Result{value=" + value + '}';
  }
}
import java.io.*;

public class ResultShutdownHookDemo {
  private static final File resultFile = new File("result.txt");
  private static final Result result = new Result();
  private static final Result oldResult = new Result();

  public static void main(String[] args) throws InterruptedException {
    loadPreviousResult();
    saveResultOnExit();
    calculateResult();
  }

  private static void loadPreviousResult() {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(resultFile)))) {
      result.setValue(Long.parseLong(bufferedReader.readLine()));
      oldResult.setValue(result.getValue());
      System.out.println("Starting with intermediate result " + result);
    }
    catch (IOException e) {
      System.err.println("Cannot read result,starting from scratch");
    }
  }

  private static void saveResultOnExit() {
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      System.out.println("Shutting down after progress from " + oldResult + " to " + result);
      try { Thread.sleep(500); }
      catch (InterruptedException ignored) {}
      try (PrintStream out = new PrintStream(new FileOutputStream(resultFile))) {
        out.println(result.getValue());
      }
      catch (IOException e) {
        System.err.println("Cannot write result");
      }
    }));
  }

  private static void calculateResult() throws InterruptedException {
    while (true) {
      result.setValue(result.getValue() + 1);
      System.out.println("Running,current result value is " + result);
      Thread.sleep(100);
    }
  }

}

此代码的作用是简单地增加一个包装在Result类中的数字,以便具有一个可变的对象,该对象可以声明为final并在关闭钩子线程中使用。它确实是由

  • 从上次运行保存的文件中加载中间结果(如果可能的话,否则从0开始计数),
  • 每100毫秒增加一次值,
  • 在JVM关闭期间将当前的中间结果写入文件中(为了演示您的问题,人为地将关闭挂钩的速度降低了500毫秒)。

现在,如果我们这样运行程序3次,总是在大约一秒钟后按Ctrl-C,输出将是这样的:

my-path> del result.txt

my-path> java -cp bin ResultShutdownHookDemo
Cannot read result,starting from scratch
Running,current result value is Result{value=1}
Running,current result value is Result{value=2}
Running,current result value is Result{value=3}
Running,current result value is Result{value=4}
Running,current result value is Result{value=5}
Running,current result value is Result{value=6}
Running,current result value is Result{value=7}
Shutting down after progress from Result{value=0} to Result{value=7}
Running,current result value is Result{value=8}
Running,current result value is Result{value=9}
Running,current result value is Result{value=10}
Running,current result value is Result{value=11}
Running,current result value is Result{value=12}

my-path> java -cp bin ResultShutdownHookDemo
Starting with intermediate result Result{value=12}
Running,current result value is Result{value=13}
Running,current result value is Result{value=14}
Running,current result value is Result{value=15}
Running,current result value is Result{value=16}
Running,current result value is Result{value=17}
Shutting down after progress from Result{value=12} to Result{value=17}
Running,current result value is Result{value=18}
Running,current result value is Result{value=19}
Running,current result value is Result{value=20}
Running,current result value is Result{value=21}
Running,current result value is Result{value=22}

my-path> java -cp bin ResultShutdownHookDemo
Starting with intermediate result Result{value=22}
Running,current result value is Result{value=23}
Running,current result value is Result{value=24}
Running,current result value is Result{value=25}
Running,current result value is Result{value=26}
Running,current result value is Result{value=27}
Running,current result value is Result{value=28}
Running,current result value is Result{value=29}
Running,current result value is Result{value=30}
Shutting down after progress from Result{value=22} to Result{value=30}
Running,current result value is Result{value=31}
Running,current result value is Result{value=32}
Running,current result value is Result{value=33}
Running,current result value is Result{value=34}
Running,current result value is Result{value=35}

我们看到以下效果:

  • 实际上,在启动关闭挂钩之后,主线程会继续运行一段时间。
  • 在第2次和第3次运行中,程序将继续运行,并且主线程最后一次将其值打印到控制台,而不是等待500 ms之前使用shutdown钩子线程打印的值。

经验教训:

  • 不要相信正常的线程在关闭挂钩运行时已经全部关闭。比赛条件可能会发生。
  • 如果您要确保首先打印的内容也是写入结果文件的内容,请在Result实例上进行同步,例如由synchronized(result)
  • 了解关闭钩子的目的是关闭资源,而不是关闭线程。因此,您确实需要使其成为线程安全的。

如您所见,在此示例中,即使没有线程安全,也没有发生任何不好的情况,因为Result实例是一个非常简单的对象,我们将其保存为一致状态。即使我们保存了一个中间结果,也不会造成任何危害,并且此后该计算将继续进行。在下一次运行时,该程序将从保存的位置重新开始其工作。

唯一丢失的工作是关闭挂钩保存结果后所做的工作,只要不影响文件或数据库之类的其他外部资源,这就不成问题。

如果是后者,则需要确保在保存中间结果之前,将通过shutdown挂钩关闭这些资源。这可能会在主应用程序线程中导致错误,但要避免不一致。您可以通过向close()添加Result方法并在关闭后调用getter或setter时引发错误来模拟此情况。因此,shutdown hook不会终止其他线程,也不会依赖于它们被终止,它只是在必要时照顾(同步并)关闭资源以提供一致性。


更新:这是其中Result类具有close方法并且已调整saveResultOnExit方法以使用它的变体。方法loadPreviousResultcalculateResult保持不变。请注意,关闭挂钩在复制要写入另一个变量的中间结果之后如何使用synchronized并关闭资源。如果要保持Result上的同步保持打开状态直到将其写入文件后,复制就不是必须的。但是,在那种情况下,您需要确保内部结果状态不能被另一个线程以任何方式更改,即资源封装很重要。

public class Result {
  private long value = 0;
  private boolean closed = false;

  public long getValue() {
    if (closed)
      throw new RuntimeException("resource closed");
    return value;
  }

  public void setValue(long value) {
    if (closed)
      throw new RuntimeException("resource closed");
    this.value = value;
  }

  public void close() {
    closed = true;
  }

  @Override
  public String toString() {
    return "Result{value=" + value + '}';
  }
}
import java.io.*;

public class ResultShutdownHookDemo {
  private static final File resultFile = new File("result.txt");
  private static final Result result = new Result();
  private static final Result oldResult = new Result();

  public static void main(String[] args) throws InterruptedException {
    loadPreviousResult();
    saveResultOnExit();
    calculateResult();
  }

  private static void loadPreviousResult() {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(resultFile)))) {
      result.setValue(Long.parseLong(bufferedReader.readLine()));
      oldResult.setValue(result.getValue());
      System.out.println("Starting with intermediate result " + result);
    }
    catch (IOException e) {
      System.err.println("Cannot read result,starting from scratch");
    }
  }

  private static void saveResultOnExit() {
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      long resultToBeSaved;
      synchronized (result) {
        System.out.println("Shutting down after progress from " + oldResult + " to " + result);
        resultToBeSaved = result.getValue();
        result.close();
      }
      try { Thread.sleep(500); }
      catch (InterruptedException ignored) {}
      try (PrintStream out = new PrintStream(new FileOutputStream(resultFile))) {
        out.println(resultToBeSaved);
      }
      catch (IOException e) {
        System.err.println("Cannot write result");
      }
    }));
  }

  private static void calculateResult() throws InterruptedException {
    while (true) {
      result.setValue(result.getValue() + 1);
      System.out.println("Running,current result value is " + result);
      Thread.sleep(100);
    }
  }

}

现在,您会在控制台上看到来自主线程的异常,因为它在关闭挂钩已经关闭资源之后尝试继续工作。但这在关闭期间无关紧要,并且可以确保我们确切地知道关闭期间写入输出文件的内容,并且在此期间没有其他线程修改要写入的对象。

my-path> del result.txt

my-path> java -cp bin ResultShutdownHookDemo
Cannot read result,current result value is Result{value=7}
Shutting down after progress from Result{value=0} to Result{value=7}
Exception in thread "main" java.lang.RuntimeException: resource closed
        at Result.getValue(Result.java:7)
        at ResultShutdownHookDemo.calculateResult(ResultShutdownHookDemo.java:51)
        at ResultShutdownHookDemo.main(ResultShutdownHookDemo.java:11)

my-path> java -cp bin ResultShutdownHookDemo
Starting with intermediate result Result{value=7}
Running,current result value is Result{value=12}
Shutting down after progress from Result{value=7} to Result{value=12}
Exception in thread "main" java.lang.RuntimeException: resource closed
        at Result.getValue(Result.java:7)
        at ResultShutdownHookDemo.calculateResult(ResultShutdownHookDemo.java:51)
        at ResultShutdownHookDemo.main(ResultShutdownHookDemo.java:11)

my-path> java -cp bin ResultShutdownHookDemo
Starting with intermediate result Result{value=12}
Running,current result value is Result{value=17}
Shutting down after progress from Result{value=12} to Result{value=17}
Exception in thread "main" java.lang.RuntimeException: resource closed
        at Result.getValue(Result.java:7)
        at ResultShutdownHookDemo.calculateResult(ResultShutdownHookDemo.java:51)
        at ResultShutdownHookDemo.main(ResultShutdownHookDemo.java:11)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res