use of io.opentelemetry.sdk.testing.time.TestClock in project opentelemetry-java by open-telemetry.
the class RateLimiterTest method testRateLimiterConcurrency.
/**
* Validates concurrent credit check correctness.
*/
@Test
void testRateLimiterConcurrency() throws InterruptedException, ExecutionException {
int numWorkers = 8;
ExecutorService executorService = Executors.newFixedThreadPool(numWorkers);
int creditsPerWorker = 1000;
TestClock clock = TestClock.create();
RateLimiter limiter = new RateLimiter(1, numWorkers * creditsPerWorker, clock);
AtomicInteger count = new AtomicInteger();
List<Future<?>> futures = new ArrayList<>(numWorkers);
for (int w = 0; w < numWorkers; ++w) {
Future<?> future = executorService.submit(() -> {
for (int i = 0; i < creditsPerWorker * 2; ++i) {
if (limiter.trySpend(1)) {
// count allowed operations
count.getAndIncrement();
}
}
});
futures.add(future);
}
for (Future<?> future : futures) {
future.get();
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);
assertThat(count.get()).withFailMessage("Exactly the allocated number of credits must be consumed").isEqualTo(numWorkers * creditsPerWorker);
assertThat(limiter.trySpend(1)).isFalse();
}
use of io.opentelemetry.sdk.testing.time.TestClock in project opentelemetry-java by open-telemetry.
the class RateLimiterTest method testRateLimiterSteadyRate.
@Test
void testRateLimiterSteadyRate() {
TestClock clock = TestClock.create();
RateLimiter limiter = new RateLimiter(5.0 / 60.0, 5.0, clock);
for (int i = 0; i < 100; i++) {
assertThat(limiter.trySpend(1.0)).isTrue();
clock.advance(Duration.ofNanos(TimeUnit.SECONDS.toNanos(20)));
}
}
use of io.opentelemetry.sdk.testing.time.TestClock in project opentelemetry-java by open-telemetry.
the class RateLimiterTest method testRateLimiterLessThanOne.
@Test
void testRateLimiterLessThanOne() {
TestClock clock = TestClock.create();
RateLimiter limiter = new RateLimiter(0.5, 0.5, clock);
assertThat(limiter.trySpend(0.25)).isTrue();
assertThat(limiter.trySpend(0.25)).isTrue();
assertThat(limiter.trySpend(0.25)).isFalse();
// move time 250ms forward, not enough credits to pay for 1.0 item
clock.advance(Duration.ofNanos(TimeUnit.MILLISECONDS.toNanos(250)));
assertThat(limiter.trySpend(0.25)).isFalse();
// move time 500ms forward, now enough credits to pay for 1.0 item
clock.advance(Duration.ofNanos(TimeUnit.MILLISECONDS.toNanos(500)));
assertThat(limiter.trySpend(0.25)).isTrue();
assertThat(limiter.trySpend(0.25)).isFalse();
// move time 5s forward, enough to accumulate credits for 10 messages, but it should still be
// capped at 2
clock.advance(Duration.ofNanos(TimeUnit.MILLISECONDS.toNanos(5000)));
assertThat(limiter.trySpend(0.25)).isTrue();
assertThat(limiter.trySpend(0.25)).isTrue();
assertThat(limiter.trySpend(0.25)).isFalse();
assertThat(limiter.trySpend(0.25)).isFalse();
assertThat(limiter.trySpend(0.25)).isFalse();
}
Aggregations