15

I am trying to throttle the number of calls to a method per second. I tried to achieve this using Guava RateLimiter.

RateLimiter rateLimiter = RateLimiter.create(1.0);//Max 1 call per sec
rateLimiter.acquire();
performOperation();//The method whose calls are to be throttled.

However the methods to the call are not limited to 1 per second but are continuous.

The throttling can be achieved using Thread.sleep() but i wish to use Guava rather that sleep().

I would like to know the right way to achieve the method call trottling using Guava RateLimiter. I have checked the documentation for RateLimiter and tried to use the same but could not achieve the desired result.

sujith
  • 665
  • 2
  • 9
  • 22

1 Answers1

30

You need to call acquire() on the same RateLimiter in every invocation, e.g. by making it available in performOperation():

public class RateLimiterTest {
    public static void main(String[] args) {
        RateLimiter limiter = RateLimiter.create(1.0);
        for (int i = 0; i < 10; i++) {
            performOperation(limiter);
        }
    }

    private static void performOperation(RateLimiter limiter) {
        limiter.acquire();
        System.out.println(new Date() + ": Beep");
    }
}

results in

Fri Aug 07 19:00:10 BST 2015: Beep
Fri Aug 07 19:00:11 BST 2015: Beep
Fri Aug 07 19:00:12 BST 2015: Beep
Fri Aug 07 19:00:13 BST 2015: Beep
Fri Aug 07 19:00:14 BST 2015: Beep
Fri Aug 07 19:00:15 BST 2015: Beep
Fri Aug 07 19:00:16 BST 2015: Beep
Fri Aug 07 19:00:17 BST 2015: Beep
Fri Aug 07 19:00:18 BST 2015: Beep
Fri Aug 07 19:00:19 BST 2015: Beep

Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
  • Hi Jens The solution worked perfectly. However i would like to one thing. Incase if the number of method calls made is higher than the rate specified , will they be discarded or will all of them be executed at the rate specified in the RateLimiter? – sujith Aug 07 '15 at 19:50
  • 2
    `rateLimiter.acquire()` will wait the right amount of time until it's time for another operation to go through. – Louis Wasserman Aug 07 '15 at 21:49
  • 4
    Hi sujith, `acquire()`'s [documentation](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/RateLimiter.html#acquire()) states that is blocks so they will all be executed at the specified rate (also, you wouldn't see 10 lines of output in my example if this wasn't the case) – Jens Hoffmann Aug 07 '15 at 21:51