RateLimiter { public void limit(final WorkFunction workFunction) { if (maxFreqGigaHz > 0) { buffer.add(System.nanoTime()); if (buffer.size() > 1) { final long sum = buffer.newest() - buffer.oldest(); final long sleepMs = Math.round((((double) buffer.maxSize() / maxFreqGigaHz) - sum) / 1.0e6d); if (sleepMs > 0) { try { Thread.sleep(sleepMs); } catch (final InterruptedException ignored) { } } } } workFunction.work(); } RateLimiter(final int maxFreqHz, final int burstFreqHz);  RateLimiter(final int maxFreqHz); void limit(final WorkFunction workFunction);  }
@Test public void testBufferSlow() { LOG.info("testBufferSlow"); final RateLimiter limiter = new RateLimiter(5); final DateTime start = DateTime.now(); for (int i = 0; i < 15; ++i) { limiter.limit(() -> { }); } final DateTime end = DateTime.now(); final long delay = end.toDate().getTime() - start.toDate().getTime(); LOG.info("Delay is {} msecs", delay); Assert.assertTrue(MathUtils.isBetween(delay, 2500, 3500)); }
@Test public void testBufferFast() { LOG.info("testBufferFast"); final RateLimiter limiter = new RateLimiter(100); final DateTime start = UTCTime.now(); for (int i = 0; i < 300; ++i) { limiter.limit(() -> { }); } final DateTime end = DateTime.now(); final long delay = end.toDate().getTime() - start.toDate().getTime(); LOG.info("Delay is {} msecs", delay); Assert.assertTrue(MathUtils.isBetween(delay, 2500, 4000)); }