the*_*evd 3 java multithreading try-catch throwable
我在java-中有以下代码
@Override
public void run() {
logger.info("Thread Started:" + this.getName());
try {
runJob();
} catch( Throwable e) {
logger.error("Exception in running thread: " + this.getName() + ", restarting job", e);
run();
}
}
public void runJob() {
while(true) {
try {
// Work here
} catch(Exception e) {
// log the exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个代码实际上是否会在每种情况下保持线程活动,这只是恢复线程的方法吗?
这是我在阅读完所有答案后想到的另一种选择.让我知道,即使发生错误,这是一个永远保持线程活着的好方法:
@Override
public void run() {
logger.info("Thread Started:" + this.getName());
while(true) {
try {
runJob();
} catch( Throwable e) {
logger.error("Exception in running thread: " + this.getName() + ", restarting job", e);
}
}
}
public void runJob() {
try {
// Work here
} catch(Exception e) {
// log the exception
}
}
Run Code Online (Sandbox Code Playgroud)
这与"线程"没什么关系.可以在异常上实现重试逻辑,这是常见的做法.
然而,捕捉Throwable显然是一件危险的事情.您可能希望重试选择错误(例如超时,连接失败等),这当然需要更好地了解您的runJob()方法如何运行.
除此之外,您的重试实现正在进行递归调用,这也可能是错误的.你最终会遇到堆栈溢出错误(以及catch你的Throwbalecatch块,它会导致奇怪的行为).而是runJob()反复循环和执行.
boolean retry = false;
do {
try {
runJob();
retry = false;
} catch (SpecificException e) { //timeout, network failure exceptions
logger.error("Exception in running thread: "
+ this.getName() + ", restarting job");
retry = true;
}
} while(retry);
Run Code Online (Sandbox Code Playgroud)
您可能还需要添加计数器以限制重试次数.
| 归档时间: |
|
| 查看次数: |
272 次 |
| 最近记录: |