-
Notifications
You must be signed in to change notification settings - Fork 0
/
TokenBucket.java
41 lines (34 loc) · 1.36 KB
/
TokenBucket.java
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
package org.CommonAlgorithms.LimitAlgorithm.TokenBucket;
import java.util.concurrent.atomic.AtomicInteger;
public class TokenBucket {
private int bucketCapacity;
private AtomicInteger currentCapacity;
public TokenBucket(int capacity, int produceRate){
this.bucketCapacity = capacity;
currentCapacity = new AtomicInteger(0);
produceToken(produceRate);
}
public void produceToken(final int producerRate){
new Thread(() -> {
while (true){
try {
Thread.sleep(1000 / producerRate);
} catch (InterruptedException e) {
System.out.println("thread sleep error, reason: " + e.getMessage());
}
if(currentCapacity.get() < bucketCapacity){
int produceTokenNum = currentCapacity.incrementAndGet();
System.out.println("token bucket algorithm, current capacity is: " + produceTokenNum);
}
}
}).start();
}
public void consumeToken(TokenBucketFunction function, int consumeToken){
if(currentCapacity.get() < consumeToken){
System.out.println("token bucket algorithm, can't not access token");
return;
}
currentCapacity.set(currentCapacity.intValue() - consumeToken);
function.handle();
}
}