Search code examples
javaguavathrottling

Google RateLimiter not Working for counter


I have case of limiting calls to 100/s.

I am thinking of using Google Guava RateLimiter. I tested it like this:-

int cps = 100;
    RateLimiter limiter = RateLimiter.create(cps);
for(int i=0;i<200;i++) {
   limiter.acquire();
   System.out.print("\rNumber of records processed = " + i+1);
}

But the code did not stop at 100 records to let 1 sec be completed. Am I doing something wrong?


Solution

  • The RateLimiter is working ok. The problem is that your output is buffered, because you are not flushing it each time. Usually, standard output is line-buffered. So if you had written

    System.out.println("Number of records processed = " + (i+1));
    

    you would have seen a pause at 100. However, what you have:

    System.out.print("\rNumber of records processed = " + i+1);

    has two problems. First, the "\r" is not taken as a new line and does not cause flushing; therefore the whole output is buffered and is printed to the console all in one go. Second, you need to put (i+1) in parentheses. What you have appends i to the string, and then appends 1 to the resultant string.