我有一段代码可能会失败也可能不会失败,我想在放弃之前尝试X次。当它失败时,它会抛出一个特定的异常,因此我认为这样可以正常工作:
int retries = 0;
while (retries < MAX_RETRIES) {
failedFlag = false;
try {
//...do some stuff...
logger.info("After commit...");
if (!failedFlag) {
logger.info("Failed flag is false, so breaking out.");
break;
}
} catch (MyException e) {
retries++;
failedFlag = true;
long sleepMillis = MILLIS_TO_SLEEP * retries;
logger.warn("Caught a failure");
logger.warn("Will sleep for " + sleepMillis + "msec and then try again.");
try {
Thread.sleep(sleepMillis);
logger.info("Done sleeping...");
logger.info("Failed flag is " + (failedFlag ? "true" : "false"));
} catch (InterruptedException e1) {
logger.warn("Caught interrupted exception while sleeping. Terminate.");
transaction.rollback();
return;
}
}
}
我遇到的问题是,在第一个catch块中对failedFlag所做的更改似乎没有持久化。失败时,线程进入睡眠状态,但是当它唤醒并重新进入try块时,failedFlag会恢复为false吗?我得到以下日志行:
2010-09-16 17:09:48,448 WARN [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Will sleep for 60000msec and then try again.
...
2010-09-16 17:10:48,449 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Done sleeping...
2010-09-16 17:10:48,450 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Failed flag is true
2010-09-16 17:10:48,453 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - After commit...
2010-09-16 17:10:48,453 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Failed flag is false, so breaking out.
Kinda在这里感到困惑……局部变量不受catch块中所做更改的影响吗?
最佳答案
您将在while循环的顶部将failFlag设置为false。