Created
May 22, 2012 16:18
-
-
Save adamv/2770047 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Allows an operation to be retried up to a maximum number of tries. | |
*/ | |
public class RetryCounter { | |
/** The maximum number of retries. */ | |
private final int maxAttempts; | |
/** The number of attempts so far. */ | |
private int attempts; | |
/** Set to true if a retry is successful. */ | |
private boolean successful; | |
/** | |
* Create a new RetryCounter. | |
* @param maxAttempts the maximum number of tries. | |
*/ | |
public RetryCounter(final int maxAttempts) { | |
if (maxAttempts < 0) { | |
throw new IllegalArgumentException("maxAttempts cannot be negative"); | |
} | |
this.maxAttempts = maxAttempts; | |
this.attempts = 0; | |
this.successful = false; | |
} | |
/** | |
* Record an attempt. | |
* @param wasSuccessful true if this attempt was successful, else false. | |
*/ | |
public void attempt(final boolean wasSuccessful) { | |
successful = wasSuccessful; | |
attempts++; | |
} | |
/** | |
* Determine if more retries should be allowed. | |
* @return true if the operation was not successful and we have not used up | |
* all the retries yet. | |
*/ | |
public boolean shouldTryAgain() { | |
return !successful && attempts < maxAttempts; | |
} | |
/** | |
* @return true if a successful attempt was recorded. | |
*/ | |
public boolean succeeded() { | |
return successful; | |
} | |
/** | |
* @return the number of attempts so far. | |
*/ | |
public int getAttempts() { | |
return attempts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment