It might be a newbie question but I could not find the reason. I have a RetryOnException
class to control the retry counts of certain tasks. I have different tasks to control and therefore I created different objects of this class.
The problem is, if I call the errorOccured()
of one object, the numberOfTriesLeft
of all my objects are changed. Seems to me that all objects are just referencing to the same object.
How can this happen and how do I fix it?
@Component
public class RetryOnException {
private int numberOfRetries; // retries
private int numberOfTriesLeft; // retries
private long timeToWait; // PauseMs
@Autowired
public RetryOnException(@Value("${exception.retries}") int numberOfRetries,
@Value("${exception.pauseMs}") long timeToWait) {
this.numberOfRetries = numberOfRetries;
this.numberOfTriesLeft = numberOfRetries;
this.timeToWait = timeToWait;
}
@Value("${exception.retries}")
private int defaultRetries;
/**
* @return true if there are tries left
*/
public boolean shouldRetry() {
return numberOfTriesLeft > 0;
}
public void errorOccured() throws Exception {
numberOfTriesLeft--;
if (!shouldRetry()) {
throw new Exception("Retry Failed: Total " + numberOfRetries
+ " attempts made at interval " + getTimeToWait()
+ "ms");
}
waitUntilNextTry();
}
public long getTimeToWait() {
return timeToWait;
}
private void waitUntilNextTry() {
try {
Thread.sleep(getTimeToWait());
} catch (InterruptedException ignored) {
}
}
public void resetRetryCount() {
numberOfTriesLeft = defaultRetries;
}
}