| 1 | /* |
| 2 | * Copyright 2006-2007 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 | * http://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.batch.retry.backoff; |
| 18 | |
| 19 | |
| 20 | /** |
| 21 | * Implementation of {@link BackOffPolicy} that pauses for a fixed period of |
| 22 | * time before continuing. A pause is implemented using {@link Thread#sleep(long)}. |
| 23 | * <p/> {@link #setBackOffPeriod(long)} is thread-safe and it is safe to call |
| 24 | * {@link #setBackOffPeriod} during execution from multiple threads, however |
| 25 | * this may cause a single retry operation to have pauses of different |
| 26 | * intervals. |
| 27 | * @author Rob Harrop |
| 28 | * @author Dave Syer |
| 29 | */ |
| 30 | public class FixedBackOffPolicy extends StatelessBackOffPolicy { |
| 31 | |
| 32 | /** |
| 33 | * Default back off period - 1000ms. |
| 34 | */ |
| 35 | private static final long DEFAULT_BACK_OFF_PERIOD = 1000L; |
| 36 | |
| 37 | /** |
| 38 | * The back off period in milliseconds. Defaults to 1000ms. |
| 39 | */ |
| 40 | private volatile long backOffPeriod = DEFAULT_BACK_OFF_PERIOD; |
| 41 | |
| 42 | |
| 43 | private Sleeper sleeper = new ObjectWaitSleeper(); |
| 44 | |
| 45 | /** |
| 46 | * Public setter for the {@link Sleeper} strategy. |
| 47 | * @param sleeper the sleeper to set defaults to {@link ObjectWaitSleeper}. |
| 48 | */ |
| 49 | public void setSleeper(Sleeper sleeper) { |
| 50 | this.sleeper = sleeper; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Set the back off period in milliseconds. Cannot be < 1. Default value |
| 55 | * is 1000ms. |
| 56 | */ |
| 57 | public void setBackOffPeriod(long backOffPeriod) { |
| 58 | this.backOffPeriod = (backOffPeriod > 0 ? backOffPeriod : 1); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Pause for the {@link #setBackOffPeriod(long)}. |
| 63 | * @throws BackOffInterruptedException if interrupted during sleep. |
| 64 | */ |
| 65 | protected void doBackOff() throws BackOffInterruptedException { |
| 66 | try { |
| 67 | sleeper.sleep(backOffPeriod); |
| 68 | } |
| 69 | catch (InterruptedException e) { |
| 70 | throw new BackOffInterruptedException("Thread interrupted while sleeping", e); |
| 71 | } |
| 72 | } |
| 73 | } |