66import io .github .bucket4j .Refill ;
77import io .github .bucket4j .local .SynchronizationStrategy ;
88import java .time .Duration ;
9- import java .util .concurrent .ScheduledFuture ;
10- import java .util .concurrent .ScheduledThreadPoolExecutor ;
11- import java .util .concurrent .TimeUnit ;
129
1310/** A light-weight token bucket implementation for RateLimiter. */
1411public class BucketRateLimiter <T > implements RateLimiter <T > {
@@ -31,9 +28,8 @@ public BucketRateLimiter(long capacity, long tokensGeneratedInPeriod, Duration p
3128
3229 @ Override
3330 public Duration when (T item ) {
34- DelayGetter delayGetter = new DelayGetter ();
35- bucket .asAsyncScheduler ().consume (1 , delayGetter ).complete (null );
36- return delayGetter .getDelay ();
31+ long overdraftNanos = bucket .consumeIgnoringRateLimits (1 );
32+ return Duration .ofNanos (overdraftNanos );
3733 }
3834
3935 @ Override
@@ -43,22 +39,4 @@ public void forget(T item) {}
4339 public int numRequeues (T item ) {
4440 return 0 ;
4541 }
46-
47- private class DelayGetter extends ScheduledThreadPoolExecutor {
48- private Duration delay = Duration .ZERO ;
49-
50- @ Override
51- public ScheduledFuture <?> schedule (Runnable command , long delay , TimeUnit unit ) {
52- this .delay = Duration .ofNanos (unit .toNanos (delay ));
53- return null ;
54- }
55-
56- private DelayGetter () {
57- super (0 );
58- }
59-
60- private Duration getDelay () {
61- return delay ;
62- }
63- }
6442}
0 commit comments