Asdfasf

Thursday, February 13, 2014

Google Guava RateLimiter

Uncontrolled power is not power. Here how throttling can be done easily using Google Guava RateLimiter

create a RateLimiter with TPS value at line 15.

Acquire RateLimiter at line 21 before submitting a job into an ExecutorService. Thats all :)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.util.concurrent.RateLimiter;


public class Test {
 static long start;
 static AtomicInteger doneCounter = new AtomicInteger(0);
 static int joblimit = 10000;
 static int TPS = 1000;
 
 public static void main(String[] args) {
  RateLimiter rateLimiter = RateLimiter.create(TPS);

  ExecutorService executorService = Executors.newCachedThreadPool();//newFixedThreadPool(10);
  start = System.currentTimeMillis();
  
  for (int i = 0; i < joblimit; i++){
   rateLimiter.acquire(); // may wait
   
   executorService.execute(new Runnable() {
    
    @Override
    public void run() {
     System.out.println("doing by " + Thread.currentThread().getName());
     int index = doneCounter.incrementAndGet();
     
     if (index == joblimit){
      System.out.println(joblimit + " job is completed in " + 
         (System.currentTimeMillis() - start) + " msec with " + TPS + " tps");
     }
    }
   });
  }
 }
  }

No comments: