Skip to content

Commit 03104e7

Browse files
committed
Generalizing CoinFlipSampler.
1 parent eb66327 commit 03104e7

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

consistent-sampling/src/test/java/io/opentelemetry/contrib/sampler/consistent56/CoinFlipSampler.java

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
import javax.annotation.concurrent.Immutable;
1717

1818
/**
19-
* A consistent sampler that delegates the decision randomly to one of its two delegates. Used by
20-
* unit tests.
19+
* A consistent sampler that delegates the decision randomly, with a predefined probability, to one
20+
* of its two delegates. Used by unit tests.
2121
*/
2222
@Immutable
2323
final class CoinFlipSampler extends ConsistentSampler {
@@ -26,20 +26,36 @@ final class CoinFlipSampler extends ConsistentSampler {
2626

2727
private final ComposableSampler samplerA;
2828
private final ComposableSampler samplerB;
29-
29+
private final double probability;
3030
private final String description;
3131

3232
/**
33-
* Constructs a new consistent CoinFlipSampler using the given two delegates.
33+
* Constructs a new consistent CoinFlipSampler using the given two delegates with equal
34+
* probability.
3435
*
3536
* @param samplerA the first delegate sampler
3637
* @param samplerB the second delegate sampler
3738
*/
3839
CoinFlipSampler(ComposableSampler samplerA, ComposableSampler samplerB) {
40+
this(samplerA, samplerB, 0.5);
41+
}
42+
43+
/**
44+
* Constructs a new consistent CoinFlipSampler using the given two delegates, and the probability
45+
* to use the first one.
46+
*
47+
* @param probability the probability to use the first sampler
48+
* @param samplerA the first delegate sampler
49+
* @param samplerB the second delegate sampler
50+
*/
51+
CoinFlipSampler(ComposableSampler samplerA, ComposableSampler samplerB, double probability) {
3952
this.samplerA = requireNonNull(samplerA);
4053
this.samplerB = requireNonNull(samplerB);
54+
this.probability = probability;
4155
this.description =
42-
"CoinFlipSampler{samplerA="
56+
"CoinFlipSampler{p="
57+
+ (float) probability
58+
+ ",samplerA="
4359
+ samplerA.getDescription()
4460
+ ','
4561
+ "samplerB="
@@ -55,7 +71,7 @@ public SamplingIntent getSamplingIntent(
5571
Attributes attributes,
5672
List<LinkData> parentLinks) {
5773

58-
if (random.nextDouble() <= 0.5) {
74+
if (random.nextDouble() < probability) {
5975
return samplerA.getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks);
6076
} else {
6177
return samplerB.getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks);

0 commit comments

Comments
 (0)