summaryrefslogtreecommitdiffstats
path: root/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ExponentialBackOffSchedulingStrategy.java
blob: 2862055834ae0ffb5b3455faad02e1cccd99f4d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package ch.boye.httpclientandroidlib.impl.client.cache;

import ch.boye.httpclientandroidlib.annotation.ThreadSafe;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * An implementation that backs off exponentially based on the number of
 * consecutive failed attempts stored in the
 * {@link AsynchronousValidationRequest}. It uses the following defaults:
 * <pre>
 *         no delay in case it was never tried or didn't fail so far
 *     6 secs delay for one failed attempt (= {@link #getInitialExpiryInMillis()})
 *    60 secs delay for two failed attempts
 *    10 mins delay for three failed attempts
 *   100 mins delay for four failed attempts
 *  ~16 hours delay for five failed attempts
 *   24 hours delay for six or more failed attempts (= {@link #getMaxExpiryInMillis()})
 * </pre>
 *
 * The following equation is used to calculate the delay for a specific revalidation request:
 * <pre>
 *     delay = {@link #getInitialExpiryInMillis()} * Math.pow({@link #getBackOffRate()}, {@link AsynchronousValidationRequest#getConsecutiveFailedAttempts()} - 1))
 * </pre>
 * The resulting delay won't exceed {@link #getMaxExpiryInMillis()}.
 *
 * @since 4.3
 */
@ThreadSafe
public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy {

    public static final long DEFAULT_BACK_OFF_RATE = 10;
    public static final long DEFAULT_INITIAL_EXPIRY_IN_MILLIS = TimeUnit.SECONDS.toMillis(6);
    public static final long DEFAULT_MAX_EXPIRY_IN_MILLIS = TimeUnit.SECONDS.toMillis(86400);

    private final long backOffRate;
    private final long initialExpiryInMillis;
    private final long maxExpiryInMillis;

    private final ScheduledExecutorService executor;

    /**
     * Create a new scheduling strategy using a fixed pool of worker threads.
     * @param cacheConfig the thread pool configuration to be used; not <code>null</code>
     * @see ch.boye.httpclientandroidlib.impl.client.cache.CacheConfig#getAsynchronousWorkersMax()
     * @see #DEFAULT_BACK_OFF_RATE
     * @see #DEFAULT_INITIAL_EXPIRY_IN_MILLIS
     * @see #DEFAULT_MAX_EXPIRY_IN_MILLIS
     */
    public ExponentialBackOffSchedulingStrategy(final CacheConfig cacheConfig) {
        this(cacheConfig,
                DEFAULT_BACK_OFF_RATE,
                DEFAULT_INITIAL_EXPIRY_IN_MILLIS,
                DEFAULT_MAX_EXPIRY_IN_MILLIS);
    }

    /**
     * Create a new scheduling strategy by using a fixed pool of worker threads and the
     * given parameters to calculated the delay.
     *
     * @param cacheConfig the thread pool configuration to be used; not <code>null</code>
     * @param backOffRate the back off rate to be used; not negative
     * @param initialExpiryInMillis the initial expiry in milli seconds; not negative
     * @param maxExpiryInMillis the upper limit of the delay in milli seconds; not negative
     * @see ch.boye.httpclientandroidlib.impl.client.cache.CacheConfig#getAsynchronousWorkersMax()
     * @see ExponentialBackOffSchedulingStrategy
     */
    public ExponentialBackOffSchedulingStrategy(
            final CacheConfig cacheConfig,
            final long backOffRate,
            final long initialExpiryInMillis,
            final long maxExpiryInMillis) {
        this(createThreadPoolFromCacheConfig(cacheConfig),
                backOffRate,
                initialExpiryInMillis,
                maxExpiryInMillis);
    }

    private static ScheduledThreadPoolExecutor createThreadPoolFromCacheConfig(
            final CacheConfig cacheConfig) {
        final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
                cacheConfig.getAsynchronousWorkersMax());
        scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        return scheduledThreadPoolExecutor;
    }

    ExponentialBackOffSchedulingStrategy(
            final ScheduledExecutorService executor,
            final long backOffRate,
            final long initialExpiryInMillis,
            final long maxExpiryInMillis) {
        this.executor = checkNotNull("executor", executor);
        this.backOffRate = checkNotNegative("backOffRate", backOffRate);
        this.initialExpiryInMillis = checkNotNegative("initialExpiryInMillis", initialExpiryInMillis);
        this.maxExpiryInMillis = checkNotNegative("maxExpiryInMillis", maxExpiryInMillis);
    }

    public void schedule(
            final AsynchronousValidationRequest revalidationRequest) {
        checkNotNull("revalidationRequest", revalidationRequest);
        final int consecutiveFailedAttempts = revalidationRequest.getConsecutiveFailedAttempts();
        final long delayInMillis = calculateDelayInMillis(consecutiveFailedAttempts);
        executor.schedule(revalidationRequest, delayInMillis, TimeUnit.MILLISECONDS);
    }

    public void close() {
        executor.shutdown();
    }

    public long getBackOffRate() {
        return backOffRate;
    }

    public long getInitialExpiryInMillis() {
        return initialExpiryInMillis;
    }

    public long getMaxExpiryInMillis() {
        return maxExpiryInMillis;
    }

    protected long calculateDelayInMillis(final int consecutiveFailedAttempts) {
        if (consecutiveFailedAttempts > 0) {
            final long delayInSeconds = (long) (initialExpiryInMillis *
                    Math.pow(backOffRate, consecutiveFailedAttempts - 1));
            return Math.min(delayInSeconds, maxExpiryInMillis);
        }
        else {
            return 0;
        }
    }

    protected static <T> T checkNotNull(final String parameterName, final T value) {
        if (value == null) {
            throw new IllegalArgumentException(parameterName + " may not be null");
        }
        return value;
    }

    protected static long checkNotNegative(final String parameterName, final long value) {
        if (value < 0) {
            throw new IllegalArgumentException(parameterName + " may not be negative");
        }
        return value;
    }
}