gpt4 book ai didi

Java - 线程崩溃后应用程序无法正常工作

转载 作者:行者123 更新时间:2023-11-30 02:56:32 24 4
gpt4 key购买 nike

我有一个 Java 应用程序,它使用多个线程,这些线程使用 ScheduledExecutorService 在给定时间后启动。每小时都有一个线程启动、执行一些工作并正确终止。但有时(例如,当 HTTP 请求不起作用时)该线程会崩溃,并且执行器服务不再启动这样的线程。然后我必须退出应用程序(使用 Ctrl-C)并再次重新启动它。

崩溃的线程是否有可能中断 ExecutorService 以实例化新线程?我不想总是检查应用程序是否仍在运行,因为它正在我的 Raspberry Pi 上运行,并且应该 24/7 运行。

也许你可以帮助我找到解决我的问题的方法!

编辑:

ExecutorService 也在它自己的线程上运行。这就是线程的启动方式:

@Override
public void run() {
threadFuture = executorService.scheduleAtFixedRate(new IntervalThread(i, p, c, a), 60, 60, TimeUnit.MINUTES);
}

这是每 60 分钟调用一次的线程:

@Override
public void run() {

try {
// do some HTTP request here
// if an error occurs, catch it and log the error message
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}

如果线程(发出 HTTP 请求)崩溃,整个 ExecutorService 将不再工作。如果我捕获所有异常,这怎么可能?

最佳答案

你的案例确实有一个解释,因为ScheduledThreadPoolExecutor

If any execution of the task encounters an exception, subsequent executions are suppressed.

尽管您正在 try{}catch(Exception) block 中执行整个任务/工作,但在某些情况下,Throwable 可能会“转义”catch block :

  1. 发生了某种错误(例如 OutOfMemoryError)。

  2. 您的日志记录代码 LOGGER.error(e.getMessage()); 在日志记录时引发了异常。

我建议您进行以下修改以了解发生了什么:

@Override
public void run() {
try {
try {
// do some HTTP request here
// if an error occurs, catch it and log the error message
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
} catch (Throwable t){
t.printStackTrace(); // this would require redirect output like java -jar my.jar >> error_log.txt
// try clean up and exit jvm with System.exit(0);

}

关于Java - 线程崩溃后应用程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37098539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com