Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;
import io.github.bucket4j.TimeMeter;
import io.github.bucket4j.local.SynchronizationStrategy;
import java.time.Duration;

Expand All @@ -28,11 +29,17 @@ public class BucketRateLimiter<T> implements RateLimiter<T> {
* @param period Period that generating specific number of tokens.
*/
public BucketRateLimiter(long capacity, long tokensGeneratedInPeriod, Duration period) {
this(capacity, tokensGeneratedInPeriod, period, TimeMeter.SYSTEM_NANOTIME);
}

BucketRateLimiter(
long capacity, long tokensGeneratedInPeriod, Duration period, TimeMeter timeMeter) {
Bandwidth bandwidth =
Bandwidth.classic(capacity, Refill.greedy(tokensGeneratedInPeriod, period));
this.bucket =
Bucket.builder()
.addLimit(bandwidth)
.withCustomTimePrecision(timeMeter)
.withSynchronizationStrategy(SynchronizationStrategy.SYNCHRONIZED)
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import io.github.bucket4j.TimeMeter;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;

class BucketRateLimiterTest {
Expand All @@ -40,16 +42,31 @@ void bucketRateLimiterBasic() {
}

@Test
void bucketRateLimiterTokenAdded() throws InterruptedException {
RateLimiter<String> rateLimiter = new BucketRateLimiter<>(2, 1, Duration.ofSeconds(2));
void bucketRateLimiterTokenAdded() {
AtomicLong currentTimeNanos = new AtomicLong(0L);
TimeMeter manualClock =
new TimeMeter() {
@Override
public long currentTimeNanos() {
return currentTimeNanos.get();
}

@Override
public boolean isWallClockBased() {
return false;
}
};

RateLimiter<String> rateLimiter =
new BucketRateLimiter<>(2, 1, Duration.ofSeconds(2), manualClock);

assertThat(rateLimiter.when("one")).isZero();
assertThat(rateLimiter.when("one")).isZero();

Duration waitDuration = rateLimiter.when("one");
assertThat(waitDuration.getSeconds()).isPositive();

Thread.sleep(4000);
currentTimeNanos.addAndGet(Duration.ofSeconds(4).toNanos());

assertThat(rateLimiter.when("two")).isZero();

Expand Down