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