|
| 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