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 @@ -64,6 +64,7 @@ public void setRate(double permitsPerSecond) {
long thisPeriod = (long) (SECONDS.toNanos(1) / permitsPerSecond);
checkState(thisPeriod > 0);
this.allowTimesPerNanos = thisPeriod;
this.lastAcquiredNanos = 0;
}

/**
Expand All @@ -75,6 +76,7 @@ public void setPeriod(Duration periodPerTimes) {
long thisPeriod = checkNotNull(periodPerTimes).toNanos();
checkState(thisPeriod > 0);
this.allowTimesPerNanos = thisPeriod;
this.lastAcquiredNanos = 0;
}

long getAllowTimesPerNanos() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Duration;

import org.junit.jupiter.api.Test;

/**
Expand Down Expand Up @@ -73,4 +75,46 @@ void test4() {
assertFalse(limiter.tryAcquire());
assertEquals(HOURS.toNanos(1), limiter.getAllowTimesPerNanos());
}

@Test
void test5() {
SimpleRateLimiter limiter = SimpleRateLimiter.create(1.0D);
new Thread(() -> {
sleepUninterruptibly(4, SECONDS);
limiter.setRate(0.5);
}).start();
int j = 0;
for (int i = 0; i < 100; i++) {
if (i % 10 == 0) {
sleepUninterruptibly(1, SECONDS);
}
if (limiter.tryAcquire()) {
j++;
}
}
assertEquals(7, j); // 4 + 6/2
assertEquals(93, limiter.getSkipCountAndClear());
assertEquals(0, limiter.getSkipCountAndClear());
}

@Test
void test6() {
SimpleRateLimiter limiter = SimpleRateLimiter.create(1.0D);
new Thread(() -> {
sleepUninterruptibly(4, SECONDS);
limiter.setPeriod(Duration.ofSeconds(2));
}).start();
int j = 0;
for (int i = 0; i < 100; i++) {
if (i % 10 == 0) {
sleepUninterruptibly(1, SECONDS);
}
if (limiter.tryAcquire()) {
j++;
}
}
assertEquals(7, j); // 4 + 6/2
assertEquals(93, limiter.getSkipCountAndClear());
assertEquals(0, limiter.getSkipCountAndClear());
}
}