-
Notifications
You must be signed in to change notification settings - Fork 1
/
RateLimit.java
58 lines (43 loc) · 1.01 KB
/
RateLimit.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
55
56
57
package duckutil;
public class RateLimit
{
private double max_bytes_per_ns;
private double last_allocated;
private double buffer_seconds;
public RateLimit(double maxBytesPerSecond, double buffer_seconds)
{
max_bytes_per_ns = maxBytesPerSecond / 1e9;
this.buffer_seconds = buffer_seconds;
resetLast();
}
private void resetLast()
{
last_allocated = Math.max(
System.nanoTime() - (buffer_seconds * 1e9),
last_allocated);
}
/**
* Returns true if a rate limit was applied
*/
public synchronized boolean waitForRate(double bytes)
{
resetLast();
double end_time = last_allocated + (bytes / max_bytes_per_ns);
double tm = System.nanoTime();
last_allocated = end_time;
if (end_time > tm)
{
long wait_tm = (long)((end_time - tm) / 1e6);
try
{
Thread.sleep(wait_tm);
}
catch(InterruptedException e)
{
throw new RuntimeException(e);
}
return true;
}
return false;
}
}