|
17 | 17 | import io.opentelemetry.sdk.trace.samplers.Sampler; |
18 | 18 | import io.opentelemetry.sdk.trace.samplers.SamplingResult; |
19 | 19 | import java.io.Closeable; |
| 20 | +import java.time.Duration; |
20 | 21 | import java.time.Instant; |
21 | 22 | import java.util.Date; |
| 23 | +import java.util.Iterator; |
22 | 24 | import java.util.List; |
23 | 25 | import java.util.Map; |
24 | 26 | import java.util.Random; |
@@ -49,7 +51,7 @@ public final class AwsXrayRemoteSampler implements Sampler, Closeable { |
49 | 51 | // Unique per-sampler client ID, generated as a random string. |
50 | 52 | private final String clientId; |
51 | 53 | private final long pollingIntervalNanos; |
52 | | - private final int jitterNanos; |
| 54 | + private final Iterator<Long> jitterNanos; |
53 | 55 |
|
54 | 56 | @Nullable private volatile ScheduledFuture<?> pollFuture; |
55 | 57 | @Nullable private volatile ScheduledFuture<?> fetchTargetsFuture; |
@@ -94,8 +96,8 @@ public static AwsXrayRemoteSamplerBuilder newBuilder(Resource resource) { |
94 | 96 | sampler = initialSampler; |
95 | 97 |
|
96 | 98 | this.pollingIntervalNanos = pollingIntervalNanos; |
97 | | - // Add ~1% of jitter. Truncating to int is safe for any practical polling interval. |
98 | | - jitterNanos = (int) (pollingIntervalNanos / 100); |
| 99 | + // Add ~1% of jitter |
| 100 | + jitterNanos = RANDOM.longs(0, pollingIntervalNanos / 100).iterator(); |
99 | 101 |
|
100 | 102 | // Execute first update right away on the executor thread. |
101 | 103 | executor.execute(this::getAndUpdateSampler); |
@@ -148,10 +150,25 @@ private void getAndUpdateSampler() { |
148 | 150 | } |
149 | 151 |
|
150 | 152 | private void scheduleSamplerUpdate() { |
151 | | - long delay = pollingIntervalNanos + RANDOM.nextInt(jitterNanos); |
| 153 | + long delay = pollingIntervalNanos + jitterNanos.next(); |
152 | 154 | pollFuture = executor.schedule(this::getAndUpdateSampler, delay, TimeUnit.NANOSECONDS); |
153 | 155 | } |
154 | 156 |
|
| 157 | + /** |
| 158 | + * returns the duration until the next scheduled sampler update or null if no next update is |
| 159 | + * scheduled yet. |
| 160 | + * |
| 161 | + * <p>only used for testing. |
| 162 | + */ |
| 163 | + @Nullable |
| 164 | + Duration getNextSamplerUpdateScheduledDuration() { |
| 165 | + ScheduledFuture<?> pollFuture = this.pollFuture; |
| 166 | + if (pollFuture == null) { |
| 167 | + return null; |
| 168 | + } |
| 169 | + return Duration.ofNanos(pollFuture.getDelay(TimeUnit.NANOSECONDS)); |
| 170 | + } |
| 171 | + |
155 | 172 | private void fetchTargets() { |
156 | 173 | if (!(sampler instanceof XrayRulesSampler)) { |
157 | 174 | throw new IllegalStateException("Programming bug."); |
|
0 commit comments