@Test public void testTimeout() throws Exception { TokenBucket tokenBucket = new TokenBucket(100, 0); Assert.assertFalse(tokenBucket.getTokens(100, 1, TimeUnit.MILLISECONDS)); Assert.assertFalse(tokenBucket.getTokens(100, 10, TimeUnit.MILLISECONDS)); Assert.assertFalse(tokenBucket.getTokens(100, 100, TimeUnit.MILLISECONDS)); Assert.assertTrue(tokenBucket.getTokens(10, 101, TimeUnit.MILLISECONDS)); tokenBucket = new TokenBucket(100, 100); Thread.sleep(200); Assert.assertTrue(tokenBucket.getTokens(20, 101, TimeUnit.MILLISECONDS)); }
public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; }
TokenBucket { public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; } }
TokenBucket { public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; } TokenBucket(long qps, long maxBucketSizeInMillis); }
TokenBucket { public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; } TokenBucket(long qps, long maxBucketSizeInMillis); void resetQPS(long qps, long maxBucketSizeInMillis); boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit); long getStoredTokens(); }
TokenBucket { public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; } TokenBucket(long qps, long maxBucketSizeInMillis); void resetQPS(long qps, long maxBucketSizeInMillis); boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit); long getStoredTokens();  }