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