MaxSamplesPerPeriod implements SamplingStrategy { @Override public boolean shouldSample() { long now = nanoClock.nanoTimeNow(); long period = now / periodLengthInNanos; synchronized (this) { if (period != currentSamplingPeriod) { currentSamplingPeriod = period; samplesInCurrentPeriod = 1; return true; } if (samplesInCurrentPeriod >= maxSamplesPerPeriod) { return false; } ++samplesInCurrentPeriod; return true; } } MaxSamplesPerPeriod(MonotonicNanoClock nanoClock, long periodLengthInNanos, long maxSamplesPerPeriod); static MaxSamplesPerPeriod withSteadyClock(long periodLengthInNanos, long maxSamplesPerPeriod); @Override boolean shouldSample();  }
@Test public void first_sample_in_period_returns_true() { var clock = MockUtils.mockedClockReturning(1000L); var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L); assertTrue(sampler.shouldSample()); }
@Test public void samples_exceeding_period_count_return_false() { var clock = MockUtils.mockedClockReturning(1000L, 1100L, 1200L); var sampler = new MaxSamplesPerPeriod(clock, 1000L, 2L); assertTrue(sampler.shouldSample()); assertTrue(sampler.shouldSample()); assertFalse(sampler.shouldSample()); }
@Test public void sample_in_new_period_returns_true() { var clock = MockUtils.mockedClockReturning(1000L, 1900L, 2000L, 2900L); var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L); assertTrue(sampler.shouldSample()); assertFalse(sampler.shouldSample()); assertTrue(sampler.shouldSample()); assertFalse(sampler.shouldSample()); }