-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThrottling.java
More file actions
48 lines (35 loc) · 1.42 KB
/
Throttling.java
File metadata and controls
48 lines (35 loc) · 1.42 KB
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
39
40
41
42
43
44
45
46
package com.ab;
import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Throttling {
public static void main(String[] args) {
// Create a RateLimiter that allows 1 permit per second
RateLimiter rateLimiter = RateLimiter.create(1.0);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new RunnableTask(rateLimiter));
executorService.execute(new RunnableTask(rateLimiter));
executorService.shutdown();
try {
executorService.awaitTermination(12, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished all threads execution");
}
private static class RunnableTask implements Runnable{
private RateLimiter rateLimiter;
public RunnableTask(RateLimiter rl) {
this.rateLimiter = rl;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
double waitTime = rateLimiter.acquire(); // Request for a permit
System.out.println("Acquired permit in " + waitTime + " seconds by " + Thread.currentThread().getName());
// Perform the action you want to rate limit
}
}
}
}