예제 #1
0
 /**
  * Acquires the given number of permits from this {@code RateLimiter}, blocking until the request
  * be granted.
  *
  * @param permits the number of permits to acquire
  */
 public void acquire(int permits) {
   checkPermits(permits);
   long microsToWait;
   synchronized (this) {
     microsToWait = reserveNextTicket(permits, readSafeMicros());
   }
   ticker.sleepMicrosUninterruptibly(microsToWait);
 }
예제 #2
0
 /**
  * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained
  * without exceeding the specified {@code timeout}, or returns {@code false} immediately (without
  * waiting) if the permits would not have been granted before the timeout expired.
  *
  * @param permits the number of permits to acquire
  * @param timeout the maximum time to wait for the permits
  * @param unit the time unit of the timeout argument
  * @return {@code true} if the permits were acquired, {@code false} otherwise
  */
 public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
   checkPermits(permits);
   long timeoutMicros = unit.toMicros(timeout);
   long microsToWait;
   synchronized (this) {
     long nowMicros = readSafeMicros();
     if (nextFreeTicketMicros > nowMicros + timeoutMicros) {
       return false;
     } else {
       microsToWait = reserveNextTicket(permits, nowMicros);
     }
   }
   ticker.sleepMicrosUninterruptibly(microsToWait);
   return true;
 }
예제 #3
0
 private long readSafeMicros() {
   return TimeUnit.NANOSECONDS.toMicros(ticker.read() - offsetNanos);
 }
예제 #4
0
 private RateLimiter(SleepingTicker ticker) {
   this.ticker = ticker;
   this.offsetNanos = ticker.read();
 }