/** * 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); }
/** * 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; }