1 /*
2 * Copyright 2006-2014 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.springframework.retry.backoff;
18
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21 import org.springframework.retry.RetryContext;
22 import org.springframework.util.ClassUtils;
23
24 /**
25 * Implementation of {@link BackOffPolicy} that increases the back off period for each
26 * retry attempt in a given set using the {@link Math#exp(double) exponential} function.
27 *
28 * This implementation is thread-safe and suitable for concurrent access. Modifications to
29 * the configuration do not affect any retry sets that are already in progress.
30 *
31 * The {@link #setInitialInterval(long)} property controls the initial value passed to
32 * {@link Math#exp(double)} and the {@link #setMultiplier(double)} property controls by
33 * how much this value is increased for each subsequent attempt.
34 *
35 * @author Rob Harrop
36 * @author Dave Syer
37 * @author Gary Russell
38 * @author Artem Bilan
39 */
40 @SuppressWarnings("serial")
41 public class ExponentialBackOffPolicy
42 implements SleepingBackOffPolicy<ExponentialBackOffPolicy> {
43
44 protected final Log logger = LogFactory.getLog(this.getClass());
45 /**
46 * The default 'initialInterval' value - 100 millisecs. Coupled with the default
47 * 'multiplier' value this gives a useful initial spread of pauses for 1-5 retries.
48 */
49 public static final long DEFAULT_INITIAL_INTERVAL = 100L;
50
51 /**
52 * The default maximum backoff time (30 seconds).
53 */
54 public static final long DEFAULT_MAX_INTERVAL = 30000L;
55
56 /**
57 * The default 'multiplier' value - value 2 (100% increase per backoff).
58 */
59 public static final double DEFAULT_MULTIPLIER = 2;
60
61 /**
62 * The initial sleep interval.
63 */
64 private volatile long initialInterval = DEFAULT_INITIAL_INTERVAL;
65
66 /**
67 * The maximum value of the backoff period in milliseconds.
68 */
69 private volatile long maxInterval = DEFAULT_MAX_INTERVAL;
70
71 /**
72 * The value to increment the exp seed with for each retry attempt.
73 */
74 private volatile double multiplier = DEFAULT_MULTIPLIER;
75
76 private Sleeper sleeper = new ThreadWaitSleeper();
77
78 /**
79 * Public setter for the {@link Sleeper} strategy.
80 * @param sleeper the sleeper to set defaults to {@link ThreadWaitSleeper}.
81 */
82 public void setSleeper(Sleeper sleeper) {
83 this.sleeper = sleeper;
84 }
85
86 public ExponentialBackOffPolicy withSleeper(Sleeper sleeper) {
87 ExponentialBackOffPolicy res = newInstance();
88 cloneValues(res);
89 res.setSleeper(sleeper);
90 return res;
91 }
92
93 protected ExponentialBackOffPolicy newInstance() {
94 return new ExponentialBackOffPolicy();
95 }
96
97 protected void cloneValues(ExponentialBackOffPolicy target) {
98 target.setInitialInterval(getInitialInterval());
99 target.setMaxInterval(getMaxInterval());
100 target.setMultiplier(getMultiplier());
101 target.setSleeper(sleeper);
102 }
103
104 /**
105 * Set the initial sleep interval value. Default is {@code 100} millisecond. Cannot be
106 * set to a value less than one.
107 *
108 * @param initialInterval the initial interval
109 */
110 public void setInitialInterval(long initialInterval) {
111 this.initialInterval = (initialInterval > 1 ? initialInterval : 1);
112 }
113
114 /**
115 * Set the multiplier value. Default is '<code>2.0</code>'. Hint: do not use values
116 * much in excess of 1.0 (or the backoff will get very long very fast).
117 * @param multiplier the multiplier
118 */
119 public void setMultiplier(double multiplier) {
120 this.multiplier = (multiplier > 1.0 ? multiplier : 1.0);
121 }
122
123 /**
124 * Setter for maximum back off period. Default is 30000 (30 seconds). the value will
125 * be reset to 1 if this method is called with a value less than 1. Set this to avoid
126 * infinite waits if backing off a large number of times (or if the multiplier is set
127 * too high).
128 *
129 * @param maxInterval in milliseconds.
130 */
131 public void setMaxInterval(long maxInterval) {
132 this.maxInterval = maxInterval > 0 ? maxInterval : 1;
133 }
134
135 /**
136 * The initial period to sleep on the first backoff.
137 * @return the initial interval
138 */
139 public long getInitialInterval() {
140 return initialInterval;
141 }
142
143 /**
144 * The maximum interval to sleep for. Defaults to 30 seconds.
145 *
146 * @return the maximum interval.
147 */
148 public long getMaxInterval() {
149 return maxInterval;
150 }
151
152 /**
153 * The multiplier to use to generate the next backoff interval from the last.
154 *
155 * @return the multiplier in use
156 */
157 public double getMultiplier() {
158 return multiplier;
159 }
160
161 /**
162 * Returns a new instance of {@link BackOffContext} configured with the 'expSeed' and
163 * 'increment' values.
164 */
165 public BackOffContext start(RetryContext context) {
166 return new ExponentialBackOffContext(this.initialInterval, this.multiplier,
167 this.maxInterval);
168 }
169
170 /**
171 * Pause for a length of time equal to ' <code>exp(backOffContext.expSeed)</code>'.
172 */
173 public void backOff(BackOffContext backOffContext)
174 throws BackOffInterruptedException {
175 ExponentialBackOffContext context = (ExponentialBackOffContext) backOffContext;
176 try {
177 long sleepTime = context.getSleepAndIncrement();
178 if (logger.isDebugEnabled()) {
179 logger.debug("Sleeping for " + sleepTime);
180 }
181 sleeper.sleep(sleepTime);
182 }
183 catch (InterruptedException e) {
184 throw new BackOffInterruptedException("Thread interrupted while sleeping", e);
185 }
186 }
187
188 static class ExponentialBackOffContext implements BackOffContext {
189
190 private final double multiplier;
191
192 private long interval;
193
194 private long maxInterval;
195
196 public ExponentialBackOffContext(long expSeed, double multiplier,
197 long maxInterval) {
198 this.interval = expSeed;
199 this.multiplier = multiplier;
200 this.maxInterval = maxInterval;
201 }
202
203 public synchronized long getSleepAndIncrement() {
204 long sleep = this.interval;
205 if (sleep > maxInterval) {
206 sleep = maxInterval;
207 }
208 else {
209 this.interval = getNextInterval();
210 }
211 return sleep;
212 }
213
214 protected long getNextInterval() {
215 return (long) (this.interval * this.multiplier);
216 }
217
218 public double getMultiplier() {
219 return multiplier;
220 }
221
222 public long getInterval() {
223 return interval;
224 }
225
226 public long getMaxInterval() {
227 return maxInterval;
228 }
229 }
230
231 public String toString() {
232 return ClassUtils.getShortName(getClass()) + "[initialInterval=" + initialInterval
233 + ", multiplier=" + multiplier + ", maxInterval=" + maxInterval + "]";
234 }
235
236 }
237