001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static java.lang.Math.max;
020import static java.util.concurrent.TimeUnit.MICROSECONDS;
021import static java.util.concurrent.TimeUnit.SECONDS;
022
023import com.google.common.annotations.Beta;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.VisibleForTesting;
026import com.google.common.base.Stopwatch;
027import com.google.common.util.concurrent.SmoothRateLimiter.SmoothBursty;
028import com.google.common.util.concurrent.SmoothRateLimiter.SmoothWarmingUp;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import java.util.Locale;
031import java.util.concurrent.TimeUnit;
032
033/**
034 * A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each
035 * {@link #acquire()} blocks if necessary until a permit is available, and then takes it. Once
036 * acquired, permits need not be released.
037 *
038 * <p>Rate limiters are often used to restrict the rate at which some physical or logical resource
039 * is accessed. This is in contrast to {@link java.util.concurrent.Semaphore} which restricts the
040 * number of concurrent accesses instead of the rate (note though that concurrency and rate are
041 * closely related, e.g. see <a href="http://en.wikipedia.org/wiki/Little%27s_law">Little's
042 * Law</a>).
043 *
044 * <p>A {@code RateLimiter} is defined primarily by the rate at which permits are issued. Absent
045 * additional configuration, permits will be distributed at a fixed rate, defined in terms of
046 * permits per second. Permits will be distributed smoothly, with the delay between individual
047 * permits being adjusted to ensure that the configured rate is maintained.
048 *
049 * <p>It is possible to configure a {@code RateLimiter} to have a warmup period during which time
050 * the permits issued each second steadily increases until it hits the stable rate.
051 *
052 * <p>As an example, imagine that we have a list of tasks to execute, but we don't want to submit
053 * more than 2 per second: <pre>   {@code
054 *  final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second"
055 *  void submitTasks(List<Runnable> tasks, Executor executor) {
056 *    for (Runnable task : tasks) {
057 *      rateLimiter.acquire(); // may wait
058 *      executor.execute(task);
059 *    }
060 *  }}</pre>
061 *
062 * <p>As another example, imagine that we produce a stream of data, and we want to cap it at 5kb per
063 * second. This could be accomplished by requiring a permit per byte, and specifying a rate of 5000
064 * permits per second: <pre>   {@code
065 *  final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second
066 *  void submitPacket(byte[] packet) {
067 *    rateLimiter.acquire(packet.length);
068 *    networkService.send(packet);
069 *  }}</pre>
070 *
071 * <p>It is important to note that the number of permits requested <i>never</i> affects the
072 * throttling of the request itself (an invocation to {@code acquire(1)} and an invocation to
073 * {@code acquire(1000)} will result in exactly the same throttling, if any), but it affects the
074 * throttling of the <i>next</i> request. I.e., if an expensive task arrives at an idle RateLimiter,
075 * it will be granted immediately, but it is the <i>next</i> request that will experience extra
076 * throttling, thus paying for the cost of the expensive task.
077 *
078 * <p>Note: {@code RateLimiter} does not provide fairness guarantees.
079 *
080 * @author Dimitris Andreou
081 * @since 13.0
082 */
083// TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision
084// would mean a maximum rate of "1MB/s", which might be small in some cases.
085@Beta
086@GwtIncompatible
087public abstract class RateLimiter {
088  /**
089   * Creates a {@code RateLimiter} with the specified stable throughput, given as
090   * "permits per second" (commonly referred to as <i>QPS</i>, queries per second).
091   *
092   * <p>The returned {@code RateLimiter} ensures that on average no more than {@code
093   * permitsPerSecond} are issued during any given second, with sustained requests being smoothly
094   * spread over each second. When the incoming request rate exceeds {@code permitsPerSecond} the
095   * rate limiter will release one permit every {@code
096   * (1.0 / permitsPerSecond)} seconds. When the rate limiter is unused, bursts of up to
097   * {@code permitsPerSecond} permits will be allowed, with subsequent requests being smoothly
098   * limited at the stable rate of {@code permitsPerSecond}.
099   *
100   * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in how many
101   *     permits become available per second
102   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero
103   */
104  // TODO(user): "This is equivalent to
105  // {@code createWithCapacity(permitsPerSecond, 1, TimeUnit.SECONDS)}".
106  public static RateLimiter create(double permitsPerSecond) {
107    /*
108     * The default RateLimiter configuration can save the unused permits of up to one second. This
109     * is to avoid unnecessary stalls in situations like this: A RateLimiter of 1qps, and 4 threads,
110     * all calling acquire() at these moments:
111     *
112     * T0 at 0 seconds
113     * T1 at 1.05 seconds
114     * T2 at 2 seconds
115     * T3 at 3 seconds
116     *
117     * Due to the slight delay of T1, T2 would have to sleep till 2.05 seconds, and T3 would also
118     * have to sleep till 3.05 seconds.
119     */
120    return create(permitsPerSecond, SleepingStopwatch.createFromSystemTimer());
121  }
122
123  @VisibleForTesting
124  static RateLimiter create(double permitsPerSecond, SleepingStopwatch stopwatch) {
125    RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */);
126    rateLimiter.setRate(permitsPerSecond);
127    return rateLimiter;
128  }
129
130  /**
131   * Creates a {@code RateLimiter} with the specified stable throughput, given as
132   * "permits per second" (commonly referred to as <i>QPS</i>, queries per second), and a <i>warmup
133   * period</i>, during which the {@code RateLimiter} smoothly ramps up its rate, until it reaches
134   * its maximum rate at the end of the period (as long as there are enough requests to saturate
135   * it). Similarly, if the {@code RateLimiter} is left <i>unused</i> for a duration of
136   * {@code warmupPeriod}, it will gradually return to its "cold" state, i.e. it will go through the
137   * same warming up process as when it was first created.
138   *
139   * <p>The returned {@code RateLimiter} is intended for cases where the resource that actually
140   * fulfills the requests (e.g., a remote server) needs "warmup" time, rather than being
141   * immediately accessed at the stable (maximum) rate.
142   *
143   * <p>The returned {@code RateLimiter} starts in a "cold" state (i.e. the warmup period will
144   * follow), and if it is left unused for long enough, it will return to that state.
145   *
146   * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in how many
147   *     permits become available per second
148   * @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up its rate,
149   *     before reaching its stable (maximum) rate
150   * @param unit the time unit of the warmupPeriod argument
151   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero or
152   *     {@code warmupPeriod} is negative
153   */
154  public static RateLimiter create(double permitsPerSecond, long warmupPeriod, TimeUnit unit) {
155    checkArgument(warmupPeriod >= 0, "warmupPeriod must not be negative: %s", warmupPeriod);
156    return create(
157        permitsPerSecond, warmupPeriod, unit, 3.0, SleepingStopwatch.createFromSystemTimer());
158  }
159
160  @VisibleForTesting
161  static RateLimiter create(
162      double permitsPerSecond,
163      long warmupPeriod,
164      TimeUnit unit,
165      double coldFactor,
166      SleepingStopwatch stopwatch) {
167    RateLimiter rateLimiter = new SmoothWarmingUp(stopwatch, warmupPeriod, unit, coldFactor);
168    rateLimiter.setRate(permitsPerSecond);
169    return rateLimiter;
170  }
171
172  /**
173   * The underlying timer; used both to measure elapsed time and sleep as necessary. A separate
174   * object to facilitate testing.
175   */
176  private final SleepingStopwatch stopwatch;
177
178  // Can't be initialized in the constructor because mocks don't call the constructor.
179  private volatile Object mutexDoNotUseDirectly;
180
181  private Object mutex() {
182    Object mutex = mutexDoNotUseDirectly;
183    if (mutex == null) {
184      synchronized (this) {
185        mutex = mutexDoNotUseDirectly;
186        if (mutex == null) {
187          mutexDoNotUseDirectly = mutex = new Object();
188        }
189      }
190    }
191    return mutex;
192  }
193
194  RateLimiter(SleepingStopwatch stopwatch) {
195    this.stopwatch = checkNotNull(stopwatch);
196  }
197
198  /**
199   * Updates the stable rate of this {@code RateLimiter}, that is, the {@code permitsPerSecond}
200   * argument provided in the factory method that constructed the {@code RateLimiter}. Currently
201   * throttled threads will <b>not</b> be awakened as a result of this invocation, thus they do not
202   * observe the new rate; only subsequent requests will.
203   *
204   * <p>Note though that, since each request repays (by waiting, if necessary) the cost of the
205   * <i>previous</i> request, this means that the very next request after an invocation to
206   * {@code setRate} will not be affected by the new rate; it will pay the cost of the previous
207   * request, which is in terms of the previous rate.
208   *
209   * <p>The behavior of the {@code RateLimiter} is not modified in any other way, e.g. if the
210   * {@code RateLimiter} was configured with a warmup period of 20 seconds, it still has a warmup
211   * period of 20 seconds after this method invocation.
212   *
213   * @param permitsPerSecond the new stable rate of this {@code RateLimiter}
214   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero
215   */
216  public final void setRate(double permitsPerSecond) {
217    checkArgument(
218        permitsPerSecond > 0.0 && !Double.isNaN(permitsPerSecond), "rate must be positive");
219    synchronized (mutex()) {
220      doSetRate(permitsPerSecond, stopwatch.readMicros());
221    }
222  }
223
224  abstract void doSetRate(double permitsPerSecond, long nowMicros);
225
226  /**
227   * Returns the stable rate (as {@code permits per seconds}) with which this {@code RateLimiter} is
228   * configured with. The initial value of this is the same as the {@code permitsPerSecond} argument
229   * passed in the factory method that produced this {@code RateLimiter}, and it is only updated
230   * after invocations to {@linkplain #setRate}.
231   */
232  public final double getRate() {
233    synchronized (mutex()) {
234      return doGetRate();
235    }
236  }
237
238  abstract double doGetRate();
239
240  /**
241   * Acquires a single permit from this {@code RateLimiter}, blocking until the request can be
242   * granted. Tells the amount of time slept, if any.
243   *
244   * <p>This method is equivalent to {@code acquire(1)}.
245   *
246   * @return time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited
247   * @since 16.0 (present in 13.0 with {@code void} return type})
248   */
249  @CanIgnoreReturnValue
250  public double acquire() {
251    return acquire(1);
252  }
253
254  /**
255   * Acquires the given number of permits from this {@code RateLimiter}, blocking until the request
256   * can be granted. Tells the amount of time slept, if any.
257   *
258   * @param permits the number of permits to acquire
259   * @return time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited
260   * @throws IllegalArgumentException if the requested number of permits is negative or zero
261   * @since 16.0 (present in 13.0 with {@code void} return type})
262   */
263  @CanIgnoreReturnValue
264  public double acquire(int permits) {
265    long microsToWait = reserve(permits);
266    stopwatch.sleepMicrosUninterruptibly(microsToWait);
267    return 1.0 * microsToWait / SECONDS.toMicros(1L);
268  }
269
270  /**
271   * Reserves the given number of permits from this {@code RateLimiter} for future use, returning
272   * the number of microseconds until the reservation can be consumed.
273   *
274   * @return time in microseconds to wait until the resource can be acquired, never negative
275   */
276  final long reserve(int permits) {
277    checkPermits(permits);
278    synchronized (mutex()) {
279      return reserveAndGetWaitLength(permits, stopwatch.readMicros());
280    }
281  }
282
283  /**
284   * Acquires a permit from this {@code RateLimiter} if it can be obtained without exceeding the
285   * specified {@code timeout}, or returns {@code false} immediately (without waiting) if the permit
286   * would not have been granted before the timeout expired.
287   *
288   * <p>This method is equivalent to {@code tryAcquire(1, timeout, unit)}.
289   *
290   * @param timeout the maximum time to wait for the permit. Negative values are treated as zero.
291   * @param unit the time unit of the timeout argument
292   * @return {@code true} if the permit was acquired, {@code false} otherwise
293   * @throws IllegalArgumentException if the requested number of permits is negative or zero
294   */
295  public boolean tryAcquire(long timeout, TimeUnit unit) {
296    return tryAcquire(1, timeout, unit);
297  }
298
299  /**
300   * Acquires permits from this {@link RateLimiter} if it can be acquired immediately without delay.
301   *
302   * <p>This method is equivalent to {@code tryAcquire(permits, 0, anyUnit)}.
303   *
304   * @param permits the number of permits to acquire
305   * @return {@code true} if the permits were acquired, {@code false} otherwise
306   * @throws IllegalArgumentException if the requested number of permits is negative or zero
307   * @since 14.0
308   */
309  public boolean tryAcquire(int permits) {
310    return tryAcquire(permits, 0, MICROSECONDS);
311  }
312
313  /**
314   * Acquires a permit from this {@link RateLimiter} if it can be acquired immediately without
315   * delay.
316   *
317   * <p>This method is equivalent to {@code tryAcquire(1)}.
318   *
319   * @return {@code true} if the permit was acquired, {@code false} otherwise
320   * @since 14.0
321   */
322  public boolean tryAcquire() {
323    return tryAcquire(1, 0, MICROSECONDS);
324  }
325
326  /**
327   * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained
328   * without exceeding the specified {@code timeout}, or returns {@code false} immediately (without
329   * waiting) if the permits would not have been granted before the timeout expired.
330   *
331   * @param permits the number of permits to acquire
332   * @param timeout the maximum time to wait for the permits. Negative values are treated as zero.
333   * @param unit the time unit of the timeout argument
334   * @return {@code true} if the permits were acquired, {@code false} otherwise
335   * @throws IllegalArgumentException if the requested number of permits is negative or zero
336   */
337  public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
338    long timeoutMicros = max(unit.toMicros(timeout), 0);
339    checkPermits(permits);
340    long microsToWait;
341    synchronized (mutex()) {
342      long nowMicros = stopwatch.readMicros();
343      if (!canAcquire(nowMicros, timeoutMicros)) {
344        return false;
345      } else {
346        microsToWait = reserveAndGetWaitLength(permits, nowMicros);
347      }
348    }
349    stopwatch.sleepMicrosUninterruptibly(microsToWait);
350    return true;
351  }
352
353  private boolean canAcquire(long nowMicros, long timeoutMicros) {
354    return queryEarliestAvailable(nowMicros) - timeoutMicros <= nowMicros;
355  }
356
357  /**
358   * Reserves next ticket and returns the wait time that the caller must wait for.
359   *
360   * @return the required wait time, never negative
361   */
362  final long reserveAndGetWaitLength(int permits, long nowMicros) {
363    long momentAvailable = reserveEarliestAvailable(permits, nowMicros);
364    return max(momentAvailable - nowMicros, 0);
365  }
366
367  /**
368   * Returns the earliest time that permits are available (with one caveat).
369   *
370   * @return the time that permits are available, or, if permits are available immediately, an
371   *     arbitrary past or present time
372   */
373  abstract long queryEarliestAvailable(long nowMicros);
374
375  /**
376   * Reserves the requested number of permits and returns the time that those permits can be used
377   * (with one caveat).
378   *
379   * @return the time that the permits may be used, or, if the permits may be used immediately, an
380   *     arbitrary past or present time
381   */
382  abstract long reserveEarliestAvailable(int permits, long nowMicros);
383
384  @Override
385  public String toString() {
386    return String.format(Locale.ROOT, "RateLimiter[stableRate=%3.1fqps]", getRate());
387  }
388
389  abstract static class SleepingStopwatch {
390    /** Constructor for use by subclasses. */
391    protected SleepingStopwatch() {}
392
393    /*
394     * We always hold the mutex when calling this. TODO(cpovirk): Is that important? Perhaps we need
395     * to guarantee that each call to reserveEarliestAvailable, etc. sees a value >= the previous?
396     * Also, is it OK that we don't hold the mutex when sleeping?
397     */
398    protected abstract long readMicros();
399
400    protected abstract void sleepMicrosUninterruptibly(long micros);
401
402    public static final SleepingStopwatch createFromSystemTimer() {
403      return new SleepingStopwatch() {
404        final Stopwatch stopwatch = Stopwatch.createStarted();
405
406        @Override
407        protected long readMicros() {
408          return stopwatch.elapsed(MICROSECONDS);
409        }
410
411        @Override
412        protected void sleepMicrosUninterruptibly(long micros) {
413          if (micros > 0) {
414            Uninterruptibles.sleepUninterruptibly(micros, MICROSECONDS);
415          }
416        }
417      };
418    }
419  }
420
421  private static void checkPermits(int permits) {
422    checkArgument(permits > 0, "Requested permits (%s) must be positive", permits);
423  }
424}