View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.classic;
28  
29  import java.util.HashMap;
30  import java.util.Map;
31  
32  import org.apache.hc.client5.http.HttpRoute;
33  import org.apache.hc.client5.http.classic.BackoffManager;
34  import org.apache.hc.core5.annotation.Experimental;
35  import org.apache.hc.core5.pool.ConnPoolControl;
36  import org.apache.hc.core5.util.Args;
37  import org.apache.hc.core5.util.TimeValue;
38  
39  /**
40   * <p>The {@code AIMDBackoffManager} applies an additive increase,
41   * multiplicative decrease (AIMD) to managing a dynamic limit to
42   * the number of connections allowed to a given host. You may want
43   * to experiment with the settings for the cooldown periods and the
44   * backoff factor to get the adaptive behavior you want.</p>
45   *
46   * <p>Generally speaking, shorter cooldowns will lead to more steady-state
47   * variability but faster reaction times, while longer cooldowns
48   * will lead to more stable equilibrium behavior but slower reaction
49   * times.</p>
50   *
51   * <p>Similarly, higher backoff factors promote greater
52   * utilization of available capacity at the expense of fairness
53   * among clients. Lower backoff factors allow equal distribution of
54   * capacity among clients (fairness) to happen faster, at the
55   * expense of having more server capacity unused in the short term.</p>
56   *
57   * @since 4.2
58   */
59  @Experimental
60  public class AIMDBackoffManager implements BackoffManager {
61  
62      private final ConnPoolControl<HttpRoute> connPerRoute;
63      private final Clock clock;
64      private final Map<HttpRoute, Long> lastRouteProbes;
65      private final Map<HttpRoute, Long> lastRouteBackoffs;
66      private TimeValue coolDown = TimeValue.ofSeconds(5L);
67      private double backoffFactor = 0.5;
68      private int cap = 2; // Per RFC 2616 sec 8.1.4
69  
70      /**
71       * Creates an {@code AIMDBackoffManager} to manage
72       * per-host connection pool sizes represented by the
73       * given {@link ConnPoolControl}.
74       * @param connPerRoute per-host routing maximums to
75       *   be managed
76       */
77      public AIMDBackoffManager(final ConnPoolControl<HttpRoute> connPerRoute) {
78          this(connPerRoute, new SystemClock());
79      }
80  
81      AIMDBackoffManager(final ConnPoolControl<HttpRoute> connPerRoute, final Clock clock) {
82          this.clock = clock;
83          this.connPerRoute = connPerRoute;
84          this.lastRouteProbes = new HashMap<>();
85          this.lastRouteBackoffs = new HashMap<>();
86      }
87  
88      @Override
89      public void backOff(final HttpRoute route) {
90          synchronized(connPerRoute) {
91              final int curr = connPerRoute.getMaxPerRoute(route);
92              final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
93              final long now = clock.getCurrentTime();
94              if (now - lastUpdate < coolDown.toMilliseconds()) {
95                  return;
96              }
97              connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
98              lastRouteBackoffs.put(route, now);
99          }
100     }
101 
102     private int getBackedOffPoolSize(final int curr) {
103         if (curr <= 1) {
104             return 1;
105         }
106         return (int)(Math.floor(backoffFactor * curr));
107     }
108 
109     @Override
110     public void probe(final HttpRoute route) {
111         synchronized(connPerRoute) {
112             final int curr = connPerRoute.getMaxPerRoute(route);
113             final int max = (curr >= cap) ? cap : curr + 1;
114             final Long lastProbe = getLastUpdate(lastRouteProbes, route);
115             final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
116             final long now = clock.getCurrentTime();
117             if (now - lastProbe < coolDown.toMilliseconds()
118                 || now - lastBackoff < coolDown.toMilliseconds()) {
119                 return;
120             }
121             connPerRoute.setMaxPerRoute(route, max);
122             lastRouteProbes.put(route, now);
123         }
124     }
125 
126     private Long getLastUpdate(final Map<HttpRoute, Long> updates, final HttpRoute route) {
127         Long lastUpdate = updates.get(route);
128         if (lastUpdate == null) {
129             lastUpdate = 0L;
130         }
131         return lastUpdate;
132     }
133 
134     /**
135      * Sets the factor to use when backing off; the new
136      * per-host limit will be roughly the current max times
137      * this factor. {@code Math.floor} is applied in the
138      * case of non-integer outcomes to ensure we actually
139      * decrease the pool size. Pool sizes are never decreased
140      * below 1, however. Defaults to 0.5.
141      * @param d must be between 0.0 and 1.0, exclusive.
142      */
143     public void setBackoffFactor(final double d) {
144         Args.check(d > 0.0 && d < 1.0, "Backoff factor must be 0.0 < f < 1.0");
145         backoffFactor = d;
146     }
147 
148     /**
149      * Sets the amount of time to wait between adjustments in
150      * pool sizes for a given host, to allow enough time for
151      * the adjustments to take effect. Defaults to 5 seconds.
152      * @param coolDown must be positive
153      */
154     public void setCoolDown(final TimeValue coolDown) {
155         Args.positive(coolDown.getDuration(), "coolDown");
156         this.coolDown = coolDown;
157     }
158 
159     /**
160      * Sets the absolute maximum per-host connection pool size to
161      * probe up to; defaults to 2 (the default per-host max).
162      * @param cap must be &gt;= 1
163      */
164     public void setPerHostConnectionCap(final int cap) {
165         Args.positive(cap, "Per host connection cap");
166         this.cap = cap;
167     }
168 
169 }