Skip to content

Commit a41c831

Browse files
committed
Addition of Throttler class & attribute in Client
1 parent 3159296 commit a41c831

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/main/java/is/swan/mcmarketapi/request/Client.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
package is.swan.mcmarketapi.request;
22

33
import is.swan.mcmarketapi.Token;
4+
import is.swan.mcmarketapi.request.sorting.Throttler;
45
import is.swan.mcmarketapi.utils.HTTPUtil;
56

67
public class Client {
78

89
private final Token token;
10+
private final Throttler throttler;
911

1012
public Client(Token token) {
1113
this.token = token;
14+
this.throttler = new Throttler();
1215
}
1316

1417
public Response send(Request request) {
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package is.swan.mcmarketapi.request.sorting;
2+
3+
import java.util.concurrent.atomic.AtomicLong;
4+
5+
public class Throttler {
6+
enum RequestType {
7+
READ, WRITE
8+
}
9+
10+
private final AtomicLong readLastRetry = new AtomicLong(0);
11+
private final AtomicLong readLastRequest = new AtomicLong(System.currentTimeMillis());
12+
13+
private final AtomicLong writeLastRetry = new AtomicLong(0);
14+
private final AtomicLong writeLastRequest = new AtomicLong(System.currentTimeMillis());
15+
16+
public long stallFor(RequestType type) {
17+
long time = System.currentTimeMillis();
18+
19+
switch (type) {
20+
case READ:
21+
return Throttler.stalForHelper(this.readLastRetry, this.readLastRequest, time);
22+
case WRITE:
23+
return Throttler.stalForHelper(this.writeLastRetry, this.writeLastRequest, time);
24+
default:
25+
return 0;
26+
}
27+
}
28+
29+
private static long stalForHelper(AtomicLong aLastRetry, AtomicLong aLastRequest, long time){
30+
long lastRetry = aLastRetry.getAcquire();
31+
long lastRequest = aLastRequest.getAcquire();
32+
33+
if (lastRetry > 0 && (time - lastRequest) < lastRetry) {
34+
return lastRetry - (time - lastRequest);
35+
} else {
36+
return 0;
37+
}
38+
}
39+
40+
public void setRead(long value) {
41+
readLastRetry.setRelease(value);
42+
readLastRequest.setRelease(System.currentTimeMillis());
43+
}
44+
45+
public void setWrite(long value) {
46+
writeLastRetry.setRelease(value);
47+
writeLastRequest.setRelease(System.currentTimeMillis());
48+
}
49+
50+
public void resetRead() {
51+
readLastRetry.setRelease(0);
52+
readLastRequest.setRelease(System.currentTimeMillis());
53+
}
54+
55+
public void resetWrite() {
56+
writeLastRetry.setRelease(0);
57+
writeLastRequest.setRelease(System.currentTimeMillis());
58+
}
59+
}

0 commit comments

Comments
 (0)