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