RRM
RRM

Reputation: 2679

Guava RateLimiter doesn't allow within permit

I am using Guava (v 32.1.1) RateLimiter as following:

    int permitsPerSecond = 10;
    RateLimiter rateLimiter = RateLimiter.create(permitsPerSecond);
    Stopwatch stopwatch = Stopwatch.createStarted();
    int i = 0;
    for (; i < permitsPerSecond; i++) {
        boolean tryAcquired = rateLimiter.tryAcquire();
        System.out.println("tryAcquired: " + tryAcquired);
    }
    System.out.println("Time elapsed: " + stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    System.out.println("No. of permit requests processed: " + i);

The output I receive is:

tryAcquired: true
tryAcquired: false
tryAcquired: false
tryAcquired: false
tryAcquired: false
Time elapsed: 2
No. of permit requests processed: 5

Since I've set permitsPerSecond to 10, shouldn't all tryAcquire() call return true?

Upvotes: 0

Views: 31

Answers (1)

David Soroko
David Soroko

Reputation: 9096

From the documentation :

A RateLimiter is defined primarily by the rate at which permits are issued. Absent additional configuration, permits will be distributed at a fixed rate, defined in terms of permits per second. Permits will be distributed smoothly, with the delay between individual permits being adjusted to ensure that the configured rate is maintained.

To get the output you expect, replace tryAcquire() with tryAcquire(1, SECONDS)

Will print similar to

tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
tryAcquired: true
Time elapsed: 905

Upvotes: 0

Related Questions