diff --git a/core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java b/core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java index a112476..d11f587 100644 --- a/core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java +++ b/core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java @@ -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; } /** @@ -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() { diff --git a/core/src/test/java/com/github/phantomthief/util/SimpleRateLimiterTest.java b/core/src/test/java/com/github/phantomthief/util/SimpleRateLimiterTest.java index d25c144..50d113b 100644 --- a/core/src/test/java/com/github/phantomthief/util/SimpleRateLimiterTest.java +++ b/core/src/test/java/com/github/phantomthief/util/SimpleRateLimiterTest.java @@ -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; /** @@ -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()); + } } \ No newline at end of file