blob: 9770fc3304a0cc998f9bdbd8eff0f3393ed6d333 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
/**
* Very basic sampling strategy which allows for sampling N requests within a fixed
* time window. No attempt is made to distribute the samples evenly within the time
* period; this is on a first-come, first-serve basis.
*/
public class MaxSamplesPerPeriod implements SamplingStrategy {
private final MonotonicNanoClock nanoClock;
private final long maxSamplesPerPeriod;
private final long periodLengthInNanos;
private long currentSamplingPeriod = 0;
private long samplesInCurrentPeriod = 0;
public MaxSamplesPerPeriod(MonotonicNanoClock nanoClock, long periodLengthInNanos, long maxSamplesPerPeriod) {
this.nanoClock = nanoClock;
this.periodLengthInNanos = periodLengthInNanos;
this.maxSamplesPerPeriod = maxSamplesPerPeriod;
}
public static MaxSamplesPerPeriod withSteadyClock(long periodLengthInNanos, long maxSamplesPerPeriod) {
// We make a reasonable assumption that System.nanoTime uses the underlying steady clock.
return new MaxSamplesPerPeriod(System::nanoTime, periodLengthInNanos, maxSamplesPerPeriod);
}
@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;
}
}
}
|