@DataProvider(value = { "42 | DAYS", "123 | SECONDS", "999 | MILLISECONDS", "3 | HOURS" }, splitBy = "\\|") @Test public void RollingWindowTimerBuilder_newMetric_creates_new_timer_with_SlidingTimeWindowReservoir_with_expected_values( long amount, TimeUnit timeUnit ) { // given RollingWindowTimerBuilder rwtb = new RollingWindowTimerBuilder(amount, timeUnit); // when Timer timer = rwtb.newMetric(); // then Histogram histogram = (Histogram) getInternalState(timer, "histogram"); Reservoir reservoir = (Reservoir) getInternalState(histogram, "reservoir"); assertThat(reservoir).isInstanceOf(SlidingTimeWindowReservoir.class); // The expected value here comes from logic in the SlidingTimeWindowReservoir constructor. assertThat(getInternalState(reservoir, "window")).isEqualTo(timeUnit.toNanos(amount) * 256); }
@DataProvider(value = { "42 | DAYS", "123 | SECONDS", "999 | MILLISECONDS", "3 | HOURS" }, splitBy = "\\|") @Test public void RollingWindowHistogramBuilder_newMetric_creates_new_histogram_with_SlidingTimeWindowReservoir_with_expected_values( long amount, TimeUnit timeUnit ) { // given RollingWindowHistogramBuilder rwhb = new RollingWindowHistogramBuilder(amount, timeUnit); // when Histogram histogram = rwhb.newMetric(); // then Reservoir reservoir = (Reservoir) getInternalState(histogram, "reservoir"); assertThat(reservoir).isInstanceOf(SlidingTimeWindowReservoir.class); // The expected value here comes from logic in the SlidingTimeWindowReservoir constructor. assertThat(getInternalState(reservoir, "window")).isEqualTo(timeUnit.toNanos(amount) * 256); }
@Test public void shouldCacheSnapshot() { Reservoir reservoir = new HdrBuilder().neverResetReservoir().buildReservoir(); reservoir.update(10); reservoir.update(20); Snapshot firstSnapshot = reservoir.getSnapshot(); reservoir.update(30); reservoir.update(40); Snapshot secondSnapshot = reservoir.getSnapshot(); assertNotSame(firstSnapshot, secondSnapshot); assertEquals(10, secondSnapshot.getMin()); assertEquals(40, secondSnapshot.getMax()); reservoir.update(9); reservoir.update(60); Snapshot thirdSnapshot = reservoir.getSnapshot(); assertNotSame(secondSnapshot, thirdSnapshot); assertEquals(9, thirdSnapshot.getMin()); assertEquals(60, thirdSnapshot.getMax()); }
@Test public void shouldCacheSnapshot() { Reservoir reservoir = new HdrBuilder().resetReservoirOnSnapshot().buildReservoir(); reservoir.update(10); reservoir.update(20); Snapshot firstSnapshot = reservoir.getSnapshot(); reservoir.update(30); reservoir.update(40); Snapshot secondSnapshot = reservoir.getSnapshot(); assertNotSame(firstSnapshot, secondSnapshot); assertEquals(30, secondSnapshot.getMin()); assertEquals(40, secondSnapshot.getMax()); reservoir.update(50); reservoir.update(60); Snapshot thirdSnapshot = reservoir.getSnapshot(); assertNotSame(secondSnapshot, thirdSnapshot); assertEquals(50, thirdSnapshot.getMin()); assertEquals(60, thirdSnapshot.getMax()); }
@Test public void testSkipBigValues() { Reservoir reservoir = new HdrBuilder().withHighestTrackableValue(100, OverflowResolver.SKIP).buildReservoir(); reservoir.update(101); Snapshot snapshot = reservoir.getSnapshot(); assertEquals(0, snapshot.getMax()); reservoir.update(100); snapshot = reservoir.getSnapshot(); assertEquals(100, snapshot.getMax()); reservoir.update(99); snapshot = reservoir.getSnapshot(); assertEquals(99, snapshot.getMin()); }
@Test public void testReduceBigValuesToMax() { Reservoir reservoir = new HdrBuilder().withHighestTrackableValue(100, OverflowResolver.REDUCE_TO_HIGHEST_TRACKABLE).buildReservoir(); reservoir.update(101); Snapshot snapshot = reservoir.getSnapshot(); assertEquals(100, snapshot.getMax()); reservoir.update(100); snapshot = reservoir.getSnapshot(); assertEquals(100, snapshot.getMax()); reservoir.update(99); snapshot = reservoir.getSnapshot(); assertEquals(99, snapshot.getMin()); }
private Summary(final String name, final String help, final String[] labelNames, final Supplier<Reservoir> reservoirSupplier, final Clock clock) { super(name, help, labelNames); this.reservoirSupplier = reservoirSupplier; this.clock = clock; }
/** * Get reservoir implementation based on the reservoir type * * @return The {@link Reservoir} implementation */ private Reservoir getReservoir() { // The Reservoir implementation is selected using a switch statement. // The ReservoirType enum is a part of YAML configuration // and foreign imports are not supported by Carbon Configuration Maven Plugin. // Therefore, the Reservoir class cannot be imported and the Reservoir // creation logic cannot be written inside ReservoirType enum. switch (reservoirType) { case EXPONENTIALLY_DECAYING: return new ExponentiallyDecayingReservoir(); case UNIFORM: return new UniformReservoir(reservoirParametersConfig.getSize()); case SLIDING_WINDOW: return new SlidingWindowReservoir(reservoirParametersConfig.getSize()); case SLIDING_TIME_WINDOW: return new SlidingTimeWindowReservoir(reservoirParametersConfig.getWindow(), reservoirParametersConfig.getWindowUnit()); case HDR_HISTOGRAM: Recorder recorder = new Recorder(reservoirParametersConfig.getNumberOfSignificantValueDigits()); if (reservoirParametersConfig.isResetOnSnapshot()) { return new HdrHistogramResetOnSnapshotReservoir(recorder); } else { return new HdrHistogramReservoir(recorder); } default: throw new RuntimeException("Invalid Reservoir Type"); } }
/** * Build a new reservoir. * * @param clock Clock to use as a time source * @param size Number of buckets to maintain * @param step Step between each bucket * @param stepUnit Time unit used in 'step' * @param delegate Delegate reservoir that min/max is being corrected for. */ public MinMaxSlidingTimeReservoir( final Clock clock, final int size, final long step, final TimeUnit stepUnit, final Reservoir delegate ) { this.clock = clock; this.size = size; this.step = stepUnit.toNanos(step); this.delegate = delegate; }
@Before public void setup() { delegate = mock(Reservoir.class); reservoir = spy(new MinMaxSlidingTimeReservoir(clock, SIZE, STEP, TimeUnit.NANOSECONDS, delegate)); doReturn(DELEGATE_SNAPSHOT).when(delegate).getSnapshot(); }
@Test(timeout = 32000) public void testThatConcurrentThreadsNotHung() throws InterruptedException { Reservoir reservoir = new HdrBuilder() .resetReservoirPeriodically(Duration.ofSeconds(1)) .buildReservoir(); HistogramUtil.runInParallel(reservoir, TimeUnit.SECONDS.toMillis(30)); }
@Test(timeout = 32000) public void testThatConcurrentThreadsNotHungWithThreeChunks() throws InterruptedException { Reservoir reservoir = new HdrBuilder() .resetReservoirPeriodicallyByChunks(Duration.ofSeconds(3), 3) .buildReservoir(); HistogramUtil.runInParallel(reservoir, TimeUnit.SECONDS.toMillis(30)); }
public static void runInParallel(Reservoir reservoir, long durationMillis) throws InterruptedException { AtomicReference<Throwable> errorRef = new AtomicReference<>(); Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors() * 2]; long start = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch(threads.length); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { try { // update reservoir 100 times and take snapshot on each cycle while (errorRef.get() == null && System.currentTimeMillis() - start < durationMillis) { for (int j = 1; j <= 10; j++) { reservoir.update(ThreadLocalRandom.current().nextInt(j)); } reservoir.getSnapshot(); } } catch (Exception e){ e.printStackTrace(); errorRef.set(e); } finally { latch.countDown(); } }); threads[i].start(); } latch.await(); //latch.await(duration.toMillis() + 4000, TimeUnit.MILLISECONDS); if (latch.getCount() > 0) { throw new IllegalStateException("" + latch.getCount() + " was not completed"); } if (errorRef.get() != null) { throw new RuntimeException(errorRef.get()); } }
@Test public void testSmartSnapshotCalculation() { double[] predefinedPercentiles = {0.5, 0.6, 0.75, 0.9, 0.95, 0.98, 0.99, 0.999}; Reservoir reservoir = new HdrBuilder().withPredefinedPercentiles(predefinedPercentiles).buildReservoir(); Snapshot snapshot = snapshotTaker.apply(reservoir); Histogram hdrHistogram = createEquivalentHistogram(); assertEquals(hdrHistogram.getStdDeviation(), snapshot.getStdDev()); assertEquals(hdrHistogram.getMinValue(), snapshot.getMin()); assertEquals(hdrHistogram.getMean(), snapshot.getMean()); assertEquals(hdrHistogram.getValueAtPercentile(50.0), (long) snapshot.getValue(0.42)); // do not defined percentile should be rounded up to first defined assertEquals(hdrHistogram.getValueAtPercentile(50.0), (long) snapshot.getMedian()); assertEquals(hdrHistogram.getMaxValue(), snapshot.getMax()); assertEquals(hdrHistogram.getValueAtPercentile(60.0), (long) snapshot.getValue(0.6)); assertEquals(hdrHistogram.getValueAtPercentile(75.0), (long) snapshot.get75thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(90.0), (long) snapshot.getValue(0.8)); // do not defined percentile should be rounded up to first defined assertEquals(hdrHistogram.getValueAtPercentile(90.0), (long) snapshot.getValue(0.9)); assertEquals(hdrHistogram.getValueAtPercentile(95.0), (long) snapshot.getValue(0.94)); // do not defined percentile should be rounded up to first defined assertEquals(hdrHistogram.getValueAtPercentile(95.0), (long) snapshot.get95thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(98.0), (long) snapshot.get98thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(99.0), (long) snapshot.get99thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(99.9), (long) snapshot.get999thPercentile()); assertEquals(hdrHistogram.getMaxValue(), (long) snapshot.getValue(0.9999)); assertEquals(predefinedPercentiles.length, snapshot.size()); assertTrue(Arrays.equals( snapshot.getValues(), new long[] { hdrHistogram.getValueAtPercentile(50.0), hdrHistogram.getValueAtPercentile(60.0), hdrHistogram.getValueAtPercentile(75.0), hdrHistogram.getValueAtPercentile(90.0), hdrHistogram.getValueAtPercentile(95.0), hdrHistogram.getValueAtPercentile(98.0), hdrHistogram.getValueAtPercentile(99.0), hdrHistogram.getValueAtPercentile(99.9), } )); }
@Test public void testFullSnapshotCalculation() { Reservoir reservoir = new HdrBuilder().withoutSnapshotOptimization().buildReservoir(); Snapshot snapshot = snapshotTaker.apply(reservoir); Histogram hdrHistogram = createEquivalentHistogram(); assertEquals(hdrHistogram.getStdDeviation(), snapshot.getStdDev()); assertEquals(hdrHistogram.getMinValue(), snapshot.getMin()); assertEquals(hdrHistogram.getMean(), snapshot.getMean()); assertEquals(hdrHistogram.getValueAtPercentile(50.0), (long) snapshot.getMedian()); assertEquals(hdrHistogram.getMaxValue(), snapshot.getMax()); assertEquals(hdrHistogram.getValueAtPercentile(60.0), (long) snapshot.getValue(0.6)); assertEquals(hdrHistogram.getValueAtPercentile(75.0), (long) snapshot.get75thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(80.0), (long) snapshot.getValue(0.8)); assertEquals(hdrHistogram.getValueAtPercentile(90.0), (long) snapshot.getValue(0.9)); assertEquals(hdrHistogram.getValueAtPercentile(94.0), (long) snapshot.getValue(0.94)); assertEquals(hdrHistogram.getValueAtPercentile(95.0), (long) snapshot.get95thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(98.0), (long) snapshot.get98thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(99.0), (long) snapshot.get99thPercentile()); assertEquals(hdrHistogram.getValueAtPercentile(99.9), (long) snapshot.get999thPercentile()); assertEquals(hdrHistogram.getTotalCount(), snapshot.size()); int i = 0; long[] values = snapshot.getValues(); for (HistogramIterationValue value : hdrHistogram.recordedValues()) { assertEquals(value.getValueIteratedTo(), values[i++]); } }
@Test public void testPassThruBigValues2() { Reservoir reservoir = new HdrBuilder() .withHighestTrackableValue(100, OverflowResolver.PASS_THRU) .buildReservoir(); reservoir.update(101); Snapshot snapshot = reservoir.getSnapshot(); assertEquals(101, snapshot.getMax()); }
@Test public void testSmartSnapshotPrinting() { Reservoir reservoir = new HdrBuilder().buildReservoir(); Snapshot snapshot = snapshotTaker.apply(reservoir); System.out.println(snapshot); snapshot.dump(new ByteArrayOutputStream()); }
@Test public void testFullSnapshotPrinting() { Reservoir reservoir = new HdrBuilder().withoutSnapshotOptimization().buildReservoir(); Snapshot snapshot = snapshotTaker.apply(reservoir); System.out.println(snapshot); snapshot.dump(new ByteArrayOutputStream()); }
/** * Create a new {@link com.codahale.metrics.Histogram} instance. These constructors are * not public in 2.2.0, so we use reflection to find them. */ public static Histogram newHistogram(Reservoir sample) { try { Constructor<?> ctor = Histogram.class.getDeclaredConstructor(Reservoir.class); ctor.setAccessible(true); return (Histogram) ctor.newInstance(sample); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testBuilder() { final MetricRegistry metricRegistry = Mockito.mock(MetricRegistry.class); DataSource dataSource = Mockito.mock(DataSource.class); PoolAdapterFactory<DataSource> poolAdapterFactory = Mockito.mock(PoolAdapterFactory.class); ConnectionProxyFactory connectionProxyFactory = Mockito.mock(ConnectionProxyFactory.class); Metrics metrics = Mockito.mock(Metrics.class); PoolAdapter poolAdapter = Mockito.mock(PoolAdapter.class); when(poolAdapterFactory.newInstance(any(ConfigurationProperties.class))).thenReturn(poolAdapter); Configuration<DataSource> configuration = new Configuration.Builder<DataSource>( "unique", dataSource, poolAdapterFactory) .setConnectionProxyFactory(connectionProxyFactory) .setJmxAutoStart(true) .setJmxEnabled(true) .setMetricLogReporterMillis(120) .setMetricsFactory(new MetricsFactory() { @Override public Metrics newInstance(ConfigurationProperties configurationProperties) { return new DropwizardMetrics(configurationProperties, metricRegistry, new ReservoirFactory() { @Override public Reservoir newInstance(Class<? extends Metric> metricClass, String metricName) { return new ExponentiallyDecayingReservoir(); } }); } }) .build(); assertSame("unique", configuration.getUniqueName()); assertSame(connectionProxyFactory, configuration.getConnectionProxyFactory()); assertTrue(configuration.isJmxAutoStart()); assertTrue(configuration.isJmxEnabled()); assertEquals(120, configuration.getMetricLogReporterMillis()); assertSame(poolAdapter, configuration.getPoolAdapter()); assertSame(dataSource, configuration.getTargetDataSource()); }
@Test public void testBuilder() { final MetricRegistry metricRegistry = Mockito.mock(MetricRegistry.class); DataSource dataSource = Mockito.mock(DataSource.class); PoolAdapterFactory<DataSource> poolAdapterFactory = Mockito.mock(PoolAdapterFactory.class); ConnectionProxyFactory connectionProxyFactory = Mockito.mock(ConnectionProxyFactory.class); Metrics metrics = Mockito.mock(Metrics.class); PoolAdapter poolAdapter = Mockito.mock(PoolAdapter.class); when(poolAdapterFactory.newInstance(any(ConfigurationProperties.class))).thenReturn(poolAdapter); Configuration<DataSource> configuration = new Configuration.Builder<DataSource>( "unique", dataSource, poolAdapterFactory) .setConnectionProxyFactory(connectionProxyFactory) .setJmxAutoStart(true) .setJmxEnabled(true) .setMetricLogReporterMillis(120) .setMetricsFactory(new MetricsFactory() { @Override public Metrics newInstance(ConfigurationProperties configurationProperties) { return new CodahaleMetrics(configurationProperties, metricRegistry, new ReservoirFactory() { @Override public Reservoir newInstance(Class<? extends Metric> metricClass, String metricName) { return new ExponentiallyDecayingReservoir(); } }); } }) .build(); assertSame("unique", configuration.getUniqueName()); assertSame(connectionProxyFactory, configuration.getConnectionProxyFactory()); assertTrue(configuration.isJmxAutoStart()); assertTrue(configuration.isJmxEnabled()); assertEquals(120, configuration.getMetricLogReporterMillis()); assertSame(poolAdapter, configuration.getPoolAdapter()); assertSame(dataSource, configuration.getTargetDataSource()); }
public static Reservoir getConfiguredReservoir(FluoConfiguration config) { String clazz = config.getString(FluoConfigurationImpl.METRICS_RESERVOIR_PROP, HdrHistogramResetOnSnapshotReservoir.class.getName()); try { return Class.forName(clazz).asSubclass(Reservoir.class).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new IllegalStateException(e); } }
protected <T extends Reservoir> T reservoir(Timer timer) throws ReflectiveOperationException{ Histogram histogram = fieldValue(timer, "histogram"); return fieldValue(histogram, "reservoir"); }
public TimerAlaCoda(Reservoir reservoir) { this(reservoir, Clock.defaultClock()); }
public TimerAlaCoda(Reservoir reservoir, Clock clock) { super(reservoir, clock); this.circonus_sub_histogram = new HistImpl(); }
public HistogramAlaCoda(Reservoir reservoir) { super(reservoir); this.circonus_sub_histogram = new HistImpl(); }
/** * Test many threads updating the reservoir. */ @Test public void testManyThreads() throws Exception { final ExecutorService pool = Executors.newWorkStealingPool(4); // last possible bucket position according to current configuration final long lastBucket = THREAD_COUNT * (SAMPLE_SIZE / CLOCK_INTERVAL) - SIZE; for (long iteration = 0L; iteration < ITERATIONS; iteration++) { final Random random = new Random(0x1234123412341234L + iteration); final DeterministicClock clock = new DeterministicClock(); final Reservoir delegate = new Reservoir() { @Override public int size() { return 0; } @Override public void update(final long value) { } @Override public Snapshot getSnapshot() { return DELEGATE_SNAPSHOT; } }; final MinMaxSlidingTimeReservoir reservoir = new MinMaxSlidingTimeReservoir(clock, SIZE, STEP, TimeUnit.NANOSECONDS, delegate); final LongAccumulator min = new LongAccumulator(Math::min, Long.MAX_VALUE); final LongAccumulator max = new LongAccumulator(Math::max, Long.MIN_VALUE); final CountDownLatch latch = new CountDownLatch(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { pool.execute(() -> { for (int s = 0; s < SAMPLE_SIZE; s++) { final long sample = random.nextLong(); if (s % CLOCK_INTERVAL == 0) { clock.add(STEP); } // check if first bucket according to the clock is after the last possible // bucket. if so, they should be taken into account. if ((reservoir.calculateFirstBucket() + SIZE) > lastBucket) { // start accumulating for reference comparison min.accumulate(sample); max.accumulate(sample); } reservoir.update(sample); } latch.countDown(); }); } // wait for all threads to complete latch.await(); final Snapshot snapshot = reservoir.getSnapshot(); assertArrayEquals("expected snapshot for iteration #" + iteration, new long[]{min.get(), 1, max.get()}, snapshot.getValues()); assertEquals("expected max for iteration #" + iteration, max.get(), snapshot.getMax()); assertEquals("expected min for iteration #" + iteration, min.get(), snapshot.getMin()); } pool.shutdown(); }
@Test public void testBasicStatisticsSlowRate() throws Exception { final DeterministicClock clock = new DeterministicClock(); int iterations = 10; int numSamples = 100; final Reservoir delegate = new ExponentiallyDecayingReservoir(1028, 0.015, clock); final MinMaxSlidingTimeReservoir reservoir = new MinMaxSlidingTimeReservoir(clock, SIZE, STEP, TimeUnit.NANOSECONDS, delegate); long exactValues[] = new long[(numSamples + 2) * iterations]; int i = 0; for (int iteration = 0; iteration < iterations; iteration++) { long maxPos = ThreadLocalRandom.current().nextInt(0, numSamples); long minPos = ThreadLocalRandom.current().nextInt(0, numSamples); for (long pos = 0; pos < numSamples; pos++) { long val = ThreadLocalRandom.current().nextLong(-VALUE_RANGE, VALUE_RANGE); reservoir.update(val); exactValues[i] = val; i++; if (pos == maxPos) { reservoir.update(MAX_VALUE); exactValues[i] = MAX_VALUE; i++; } if (pos == minPos) { reservoir.update(MIN_VALUE); exactValues[i] = MIN_VALUE; i++; } } final Snapshot snapshot = reservoir.getSnapshot(); assertEquals(MAX_VALUE, snapshot.getMax()); assertEquals(MIN_VALUE, snapshot.getMin()); long expectedValues[] = Arrays.copyOf(exactValues, i); Arrays.sort(expectedValues); long reservoirValues[] = Arrays.copyOf(snapshot.getValues(), snapshot.getValues().length); Arrays.sort(reservoirValues); assertArrayEquals(expectedValues, reservoirValues); } }
@Test public void testBasicStatisticsHighRate() throws Exception { final DeterministicClock clock = new DeterministicClock(); int iterations = 2; for (int iteration = 0; iteration < iterations; iteration++) { final Reservoir delegate = new ExponentiallyDecayingReservoir(1028, 0.015, clock); final MinMaxSlidingTimeReservoir reservoir = new MinMaxSlidingTimeReservoir(clock, SIZE, STEP, TimeUnit.NANOSECONDS, delegate); int numSamples = 1000000; int clockInterval = numSamples / SIZE; long exactValues[] = new long[numSamples + 2]; long maxPos = ThreadLocalRandom.current().nextInt(0, numSamples); long minPos = ThreadLocalRandom.current().nextInt(0, numSamples); int i = 0; for (long pos = 0; pos < numSamples; pos++) { if (pos > 0 && pos % clockInterval == 0) { clock.add(STEP); } long val = ThreadLocalRandom.current().nextLong(-VALUE_RANGE, VALUE_RANGE); reservoir.update(val); exactValues[i] = val; i++; // Insert an extreme max / min value at a random point in the reservoir if (pos == maxPos) { reservoir.update(MAX_VALUE); exactValues[i] = MAX_VALUE; i++; } if (pos == minPos) { reservoir.update(MIN_VALUE); exactValues[i] = MIN_VALUE; i++; } } final Snapshot snapshot = reservoir.getSnapshot(); assertEquals("Max value", MAX_VALUE, snapshot.getMax()); assertEquals("Min value", MIN_VALUE, snapshot.getMin()); final long actualValues[] = Arrays.copyOf(snapshot.getValues(), snapshot.getValues().length); assertTrue("Reservoir contains values", actualValues.length > 1000); final Set<Long> exactValueSet = new HashSet<>(); for (i = 0; i < exactValues.length; i++) { exactValueSet.add(exactValues[i]); } assertTrue("Only known values in the reservoir", Arrays .stream(actualValues) .filter(value -> !exactValueSet.contains(value)) .count() == 0); final long zeroValueRange = (VALUE_RANGE * 10) / 100; assertThat("Mean value is within 10% error rate of 0", (long) snapshot.getMean(), allOf(greaterThan(-zeroValueRange), lessThan(zeroValueRange))); final long stdDev = (long) snapshot.getStdDev(); assertThat("Mean deviation is more than 40% of value range", stdDev, greaterThan((VALUE_RANGE * 40) / 100)); assertThat("Mean deviation is less than the max value range", stdDev, lessThan(MAX_VALUE)); final Snapshot snapshot2 = reservoir.getSnapshot(); assertArrayEquals("Two calls to get snapshot results in same data", snapshot.getValues(), snapshot2.getValues()); } }
SnapshotCachingReservoir(Reservoir target, long cachingDurationMillis, Clock clock) { this.cachingSupplier = new CachingSupplier<>(cachingDurationMillis, clock, target::getSnapshot); this.target = target; }
@Test public void test() { AtomicLong time = new AtomicLong(0); Clock wallClock = Clock.mock(time); Reservoir reservoir = new HdrBuilder(wallClock) .resetReservoirPeriodically(Duration.ofMillis(1000)) .withBackgroundExecutor(MockExecutor.INSTANCE) .buildReservoir(); reservoir.update(10); reservoir.update(20); Snapshot snapshot = reservoir.getSnapshot(); assertEquals(10, snapshot.getMin()); assertEquals(20, snapshot.getMax()); time.getAndAdd(900); // 900 reservoir.update(30); reservoir.update(40); snapshot = reservoir.getSnapshot(); assertEquals(10, snapshot.getMin()); assertEquals(40, snapshot.getMax()); time.getAndAdd(99); // 999 reservoir.update(8); reservoir.update(60); snapshot = reservoir.getSnapshot(); assertEquals(8, snapshot.getMin()); assertEquals(60, snapshot.getMax()); time.getAndAdd(1); // 1000 reservoir.update(70); reservoir.update(80); snapshot = reservoir.getSnapshot(); assertEquals(70, snapshot.getMin()); assertEquals(80, snapshot.getMax()); time.getAndAdd(1001); // 2001 reservoir.update(90); reservoir.update(100); snapshot = reservoir.getSnapshot(); assertEquals(90, snapshot.getMin()); assertEquals(100, snapshot.getMax()); time.getAndAdd(1000); // 3001 snapshot = reservoir.getSnapshot(); assertEquals(0, snapshot.getMin()); assertEquals(0, snapshot.getMax()); time.getAndAdd(1); // 3002 reservoir.update(42); snapshot = reservoir.getSnapshot(); assertEquals(42, snapshot.getMin()); assertEquals(42, snapshot.getMax()); time.getAndAdd(2000); // 5002 snapshot = reservoir.getSnapshot(); assertEquals(0, snapshot.getMin()); assertEquals(0, snapshot.getMax()); }
@Test public void test() { AtomicLong time = new AtomicLong(0); Clock wallClock = Clock.mock(time); Reservoir reservoir = new HdrBuilder(wallClock) .resetReservoirPeriodicallyByChunks(Duration.ofMillis(3000), 3) .withBackgroundExecutor(MockExecutor.INSTANCE) .buildReservoir(); reservoir.update(10); reservoir.update(20); Snapshot snapshot = reservoir.getSnapshot(); assertEquals(10, snapshot.getMin()); assertEquals(20, snapshot.getMax()); time.getAndAdd(900); // 900 reservoir.update(30); reservoir.update(40); snapshot = reservoir.getSnapshot(); assertEquals(10, snapshot.getMin()); assertEquals(40, snapshot.getMax()); time.getAndAdd(99); // 999 reservoir.update(9); reservoir.update(60); snapshot = reservoir.getSnapshot(); assertEquals(9, snapshot.getMin()); assertEquals(60, snapshot.getMax()); time.getAndAdd(1); // 1000 reservoir.update(12); reservoir.update(70); snapshot = reservoir.getSnapshot(); assertEquals(9, snapshot.getMin()); assertEquals(70, snapshot.getMax()); time.getAndAdd(1001); // 2001 reservoir.update(13); reservoir.update(80); snapshot = reservoir.getSnapshot(); assertEquals(9, snapshot.getMin()); assertEquals(80, snapshot.getMax()); time.getAndAdd(1000); // 3001 snapshot = reservoir.getSnapshot(); assertEquals(9, snapshot.getMin()); assertEquals(80, snapshot.getMax()); time.getAndAdd(999); // 4000 snapshot = reservoir.getSnapshot(); assertEquals(12, snapshot.getMin()); assertEquals(80, snapshot.getMax()); reservoir.update(1); reservoir.update(200); snapshot = reservoir.getSnapshot(); assertEquals(1, snapshot.getMin()); assertEquals(200, snapshot.getMax()); time.getAndAdd(10000); // 14000 snapshot = reservoir.getSnapshot(); assertEquals(0, snapshot.getMin()); assertEquals(0, snapshot.getMax()); reservoir.update(3); time.addAndGet(3999); // 17999 snapshot = reservoir.getSnapshot(); assertEquals(3, snapshot.getMax()); time.addAndGet(1); // 18000 snapshot = reservoir.getSnapshot(); assertEquals(0, snapshot.getMax()); }
@Test public void whenCachingDurationSpecifiedThenReservoirShouldBeDecoratedByProxy() { Reservoir reservoir = new HdrBuilder().withSnapshotCachingDuration(Duration.ofSeconds(5)).buildReservoir(); assertTrue(reservoir instanceof SnapshotCachingReservoir); }
@Test public void zeroDurationShouldNotLeadToCreateDecorator() { Reservoir reservoir = new HdrBuilder().withSnapshotCachingDuration(Duration.ZERO).buildReservoir(); assertFalse(reservoir instanceof SnapshotCachingReservoir); }
@Test public void byDefaultCachingShouldBeTurnedOf() { Reservoir reservoir = new HdrBuilder().buildReservoir(); assertFalse(reservoir instanceof SnapshotCachingReservoir); }
@Test(expected = UnsupportedOperationException.class) public void sizeMethodShouldBeUndefined() { Reservoir reservoir = new HdrBuilder().withSnapshotCachingDuration(Duration.ofSeconds(10)).buildReservoir(); reservoir.size(); }
@Test public void shouldCacheSnapshot() { AtomicLong time = new AtomicLong(System.currentTimeMillis()); Clock wallClock = Clock.mock(time); Reservoir reservoir = new HdrBuilder(wallClock) .resetReservoirOnSnapshot() .withSnapshotCachingDuration(Duration.ofMillis(1000)) .buildReservoir(); reservoir.update(10); reservoir.update(20); Snapshot firstSnapshot = reservoir.getSnapshot(); time.getAndAdd(900); reservoir.update(30); reservoir.update(40); Snapshot firstCachedSnapshot = reservoir.getSnapshot(); assertSame(firstSnapshot, firstCachedSnapshot); assertEquals(10, firstCachedSnapshot.getMin()); assertEquals(20, firstCachedSnapshot.getMax()); time.getAndAdd(99); reservoir.update(50); reservoir.update(60); Snapshot secondCachedSnapshot = reservoir.getSnapshot(); assertSame(firstSnapshot, secondCachedSnapshot); assertEquals(10, secondCachedSnapshot.getMin()); assertEquals(20, secondCachedSnapshot.getMax()); time.getAndAdd(1); reservoir.update(70); reservoir.update(80); Snapshot firstNewSnapshot = reservoir.getSnapshot(); assertNotSame(firstSnapshot, firstNewSnapshot); assertEquals(30, firstNewSnapshot.getMin()); assertEquals(80, firstNewSnapshot.getMax()); time.getAndAdd(1001); reservoir.update(90); reservoir.update(100); Snapshot secondNewSnapshot = reservoir.getSnapshot(); assertNotSame(firstNewSnapshot, secondNewSnapshot); assertEquals(90, secondNewSnapshot.getMin()); assertEquals(100, secondNewSnapshot.getMax()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testPassThruBigValues() { Reservoir reservoir = new HdrBuilder().withHighestTrackableValue(100, OverflowResolver.PASS_THRU).buildReservoir(); reservoir.update(100000); }
protected Reservoir createReservoir() { return new ExponentiallyDecayingReservoir(); }
public Reservoir getAverageExecutionTimeReservoir() { return averageExecutionTime; }