|
| 1 | +package org.baeldung.guava; |
| 2 | + |
| 3 | + |
| 4 | +import com.google.common.util.concurrent.RateLimiter; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import java.time.ZonedDateTime; |
| 8 | +import java.util.concurrent.TimeUnit; |
| 9 | +import java.util.stream.IntStream; |
| 10 | + |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; |
| 12 | + |
| 13 | +public class RateLimiterUnitTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() { |
| 17 | + //given |
| 18 | + RateLimiter rateLimiter = RateLimiter.create(100); |
| 19 | + |
| 20 | + //when |
| 21 | + long startTime = ZonedDateTime.now().getSecond(); |
| 22 | + IntStream.range(0, 1000).forEach(i -> { |
| 23 | + rateLimiter.acquire(); |
| 24 | + doSomeLimitedOperation(); |
| 25 | + }); |
| 26 | + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; |
| 27 | + |
| 28 | + //then |
| 29 | + assertThat(elapsedTimeSeconds >= 10); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() { |
| 34 | + //given |
| 35 | + RateLimiter rateLimiter = RateLimiter.create(2); |
| 36 | + |
| 37 | + //when |
| 38 | + long startTime = ZonedDateTime.now().getSecond(); |
| 39 | + rateLimiter.acquire(1); |
| 40 | + doSomeLimitedOperation(); |
| 41 | + rateLimiter.acquire(1); |
| 42 | + doSomeLimitedOperation(); |
| 43 | + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; |
| 44 | + |
| 45 | + //then |
| 46 | + assertThat(elapsedTimeSeconds <= 1); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() { |
| 51 | + //given |
| 52 | + RateLimiter rateLimiter = RateLimiter.create(100); |
| 53 | + |
| 54 | + //when |
| 55 | + long startTime = ZonedDateTime.now().getSecond(); |
| 56 | + rateLimiter.acquire(100); |
| 57 | + doSomeLimitedOperation(); |
| 58 | + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; |
| 59 | + |
| 60 | + //then |
| 61 | + assertThat(elapsedTimeSeconds <= 1); |
| 62 | + } |
| 63 | + |
| 64 | + @Test |
| 65 | + public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() { |
| 66 | + //given |
| 67 | + RateLimiter rateLimiter = RateLimiter.create(1); |
| 68 | + |
| 69 | + //when |
| 70 | + boolean result = rateLimiter.tryAcquire(2, 1, TimeUnit.SECONDS); |
| 71 | + |
| 72 | + //then |
| 73 | + assertThat(result).isFalse(); |
| 74 | + |
| 75 | + } |
| 76 | + |
| 77 | + private void doSomeLimitedOperation() { |
| 78 | + //some computing |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments