-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenBucket.java
54 lines (41 loc) · 1.29 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
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.concurrent.atomic.AtomicLong;
/**
* A Token Bucket (https://en.wikipedia.org/wiki/Token_bucket)
*
* This thread-safe bucket should support the following methods:
*
* - take(n): remove n tokens from the bucket (blocks until n tokens are available and taken)
* - set(n): set the bucket to contain n tokens (to allow "hard" rate limiting)
* - add(n): add n tokens to the bucket (to allow "soft" rate limiting)
*
*/
class TokenBucket {
private long numTokens;
private static TokenBucket instance;
private TokenBucket() {
this.numTokens = 0;
}
// singleton
synchronized static TokenBucket getInstance() {
if(instance == null){
instance = new TokenBucket();
}
return instance;
}
synchronized void take(long tokens) throws InterruptedException {
while(this.numTokens < tokens) {
// wait for enough tokens to be available
this.wait();
}
// if we reach here, then there are enough tokens to be taken
this.numTokens -= tokens;
}
synchronized void add(long tokens) {
this.numTokens += tokens;
this.notify();
}
synchronized void set(long tokens) {
this.numTokens = tokens;
this.notify();
}
}