java - Throttling method calls using Guava RateLimiter class -


i trying throttle number of calls method per second. tried achieve using guava ratelimiter.

ratelimiter ratelimiter = ratelimiter.create(1.0);//max 1 call per sec ratelimiter.acquire(); performoperation();//the method calls throttled. 

however methods call not limited 1 per second continuous.

the throttling can achieved using thread.sleep() wish use guava rather sleep().

i know right way achieve method call trottling using guava ratelimiter. have checked documentation ratelimiter , tried use same not achieve desired result.

you need call acquire() on same ratelimiter in every invocation, e.g. making available in performoperation():

public class ratelimitertest {     public static void main(string[] args) {         ratelimiter limiter = ratelimiter.create(1.0);         (int = 0; < 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


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -