gpt4 book ai didi

java - 如何使手动重试线程安全

转载 作者:行者123 更新时间:2023-11-30 05:21:58 25 4
gpt4 key购买 nike

我正在尝试手动重试。但我觉得代码不是线程安全的。任何人都可以提供有关如何使其线程安全的建议

while (retryCounter < maxRetries) {
try {
//TODO - add delay with config
Thread.sleep(3000);
t.run();
break;
} catch (Exception e) {
retryCounter++;
//TODO - Add audit logs
if (retryCounter >= maxRetries) {
LOG.info("Max retries exceeded");
//TODO - remove exception add audit logs
throw new RuntimeException("Max retry exceeded");
}
}
}

提前致谢

最佳答案

正如 @ SteffenJacobs 所指出的,t.run 不会在单独的线程上执行运行逻辑,而是在进行调用的线程上执行。如果将 t.run 替换为 t.start,则运行逻辑将在不同的线程上异步执行,这意味着该新线程中的异常线程永远不会被您的 catch block 处理。例如下面的代码:

public static void main(String[] args) {
int retryCounter = 0;
int maxRetries = 3;

Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("..." + Thread.currentThread());
throw new RuntimeException("Thrown by me!!!");
}});

while (retryCounter < maxRetries) {
try {
Thread.sleep(3000);
System.out.println("***" + Thread.currentThread());
t.start();
break;
} catch (Exception e) {
System.out.println("retrying attempt " + retryCounter);
System.out.println(e);
retryCounter++;
if (retryCounter >= maxRetries) {
throw new RuntimeException("Max retry exceeded");
}
} finally {
System.out.println("in finally");
}
}
}

打印:

***Thread[main,5,main]
in finally
...Thread[Thread-0,5,main]
Exception in thread "Thread-0" java.lang.RuntimeException: Thrown by me!!!
...
Process finished with exit code 0

底线 - 要检测线程任务中的错误,您需要考虑不同的方法。您可以考虑使用 Future ( https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html )。在这种情况下,您的任务将需要返回其执行状态,同时启动它们的代码等待 Future.get ,检查状态并根据需要重新运行任务。

关于java - 如何使手动重试线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419781/

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