2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.energidataservice.internal.retry.strategy;
15 import java.time.Duration;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.energidataservice.internal.retry.RetryStrategy;
22 * This implements a {@link RetryStrategy} for exponential backoff with jitter.
24 * @author Jacob Laursen - Initial contribution
27 public class ExponentialBackoff implements RetryStrategy {
29 private int attempts = 0;
30 private int factor = 2;
31 private double jitter = 0.0;
32 private Duration minimum = Duration.ofMillis(100);
33 private Duration maximum = Duration.ofHours(6);
35 public ExponentialBackoff() {
39 public Duration getDuration() {
40 long minimum = this.minimum.toMillis();
41 long maximum = this.maximum.toMillis();
42 long duration = minimum * (long) Math.pow(this.factor, this.attempts++);
44 double rand = Math.random();
45 if ((((int) Math.floor(rand * 10)) & 1) == 0) {
46 duration += (long) (rand * jitter * duration);
48 duration -= (long) (rand * jitter * duration);
51 if (duration < minimum) {
54 if (duration > maximum) {
57 return Duration.ofMillis(duration);
60 public ExponentialBackoff withFactor(int factor) {
65 public ExponentialBackoff withJitter(double jitter) {
70 public ExponentialBackoff withMinimum(Duration minimum) {
71 this.minimum = minimum;
75 public ExponentialBackoff withMaximum(Duration maximum) {
76 this.maximum = maximum;
81 public boolean equals(@Nullable Object o) {
85 if (!(o instanceof ExponentialBackoff)) {
88 ExponentialBackoff other = (ExponentialBackoff) o;
90 return this.factor == other.factor && this.jitter == other.jitter && this.minimum.equals(other.minimum)
91 && this.maximum.equals(other.maximum);
95 public final int hashCode() {
98 result = prime * result + factor;
99 result = prime * result + (int) jitter * 100;
100 result = prime * result + (int) minimum.toMillis();
101 result = prime * result + (int) maximum.toMillis();