| 18 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 19 | |
| 20 | public class DefaultRetryer implements Retryer { |
| 21 | |
| 22 | private final int maxAttempts; |
| 23 | private final long period; |
| 24 | private final long maxPeriod; |
| 25 | int attempt; |
| 26 | long sleptForMillis; |
| 27 | |
| 28 | public DefaultRetryer() { |
| 29 | this(100, SECONDS.toMillis(1), 5); |
| 30 | } |
| 31 | |
| 32 | public DefaultRetryer(long period, long maxPeriod, int maxAttempts) { |
| 33 | this.period = period; |
| 34 | this.maxPeriod = maxPeriod; |
| 35 | this.maxAttempts = maxAttempts; |
| 36 | this.attempt = 1; |
| 37 | } |
| 38 | |
| 39 | // visible for testing; |
| 40 | protected long currentTimeMillis() { |
| 41 | return System.currentTimeMillis(); |
| 42 | } |
| 43 | |
| 44 | public void continueOrPropagate(RetryableException e) { |
| 45 | if (attempt++ >= maxAttempts) { |
| 46 | throw e; |
| 47 | } |
| 48 | |
| 49 | long interval; |
| 50 | if (e.retryAfter() != null) { |
| 51 | interval = e.retryAfter() - currentTimeMillis(); |
| 52 | if (interval > maxPeriod) { |
| 53 | interval = maxPeriod; |
| 54 | } |
| 55 | if (interval < 0) { |
| 56 | return; |
| 57 | } |
| 58 | } else { |
| 59 | interval = nextMaxInterval(); |
| 60 | } |
| 61 | try { |
| 62 | Thread.sleep(interval); |
| 63 | } catch (InterruptedException ignored) { |
| 64 | Thread.currentThread().interrupt(); |
| 65 | throw e; |
| 66 | } |
| 67 | sleptForMillis += interval; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Calculates the time interval to a retry attempt.<br> |
| 72 | * The interval increases exponentially with each attempt, at a rate of nextInterval *= 1.5 (where |
| 73 | * 1.5 is the backoff factor), to the maximum interval. |
| 74 | * |
| 75 | * @return time in milliseconds from now until the next attempt. |
| 76 | */ |
| 77 | long nextMaxInterval() { |
nothing calls this directly
no outgoing calls
no test coverage detected