Hello,
I have a piece of code that may or may not fail, which I want to try X number of times before giving up. When it fails, it throws a specific Exception, so I figured something like this would work:
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;
}
}
}
The problem I'm having is that the change made to failedFlag in the first catch block doesn't seem to persist. Upon failure, the thread sleeps, but when it wakes up and re-enters the try block, the failedFlag reverts back to false? I get the following log lines:
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 boggled here... Are local variables unaffected by changes made in catch blocks?