Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Ratelimiter tryAcquire returns true only for the first call(any number of permits)?

Tags:

java

guava

I am using Guava 18.0 RateLimiter:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire());
    _log.info("Acquired two " + lt.tryAcquire());
}

The output is:

: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

Specifying the number of permits to 12:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire(12));
    _log.info("Acquired two " + lt.tryAcquire());
}

The output is:

: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

Why is this happening?

like image 322
Poornima Avatar asked Oct 28 '25 10:10

Poornima


1 Answers

The behaviour of the first example is expected because:

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);
_log.info("Acquired one " + lt.tryAcquire());

// waiting 1/2 second we will be able to get the second permit
Thread.sleep(500);
_log.info("Acquired two " + lt.tryAcquire());

The output is:

Acquired one true
Acquired two true

From the Guava docs:

The returned RateLimiter ensures that on average no more than permitsPerSecond are issued during any given second, with sustained requests being smoothly spread over each second.

The behaviour of the second example is expected too because to successfully get the single permit on the second "Acquire" we need to wait around 6 seconds (= 12 / 2)

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);

// trying to acquire 12 permits
_log.info("Acquired one " + lt.tryAcquire(12));

// waiting 12 / 2 seconds in order to be able to get the second permit
Thread.sleep(6000);
_log.info("Acquired two " + lt.tryAcquire());

The output is:

Acquired one true
Acquired two true

Trying to acquire the last permit waiting less than 6 seconds would fail, that is why lt.tryAcquire() in your example returns false.

like image 85
Filippo Vitale Avatar answered Oct 29 '25 23:10

Filippo Vitale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!