Skip to content
This repository was archived by the owner on Jan 14, 2026. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import com.tdunning.math.stats.TDigest;

import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicReference;

/**
* Semantic Metric implementation of {@link Distribution}.
Expand All @@ -50,23 +49,24 @@
public class SemanticMetricDistribution implements Distribution {

private static final int COMPRESSION_DEFAULT_LEVEL = 100;
private final AtomicReference<TDigest> distRef;
private volatile TDigest dist;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since dist is covered by synchronized everywhere, does it really need to be a volatile?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 85 references dist without being synchronized, so the read might see a stale copy

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd make it synchronized as well instead (like this e.g.).


SemanticMetricDistribution() {
this.distRef = new AtomicReference<>(create());
this.dist = create();
}

@Override
public synchronized void record(double val) {
distRef.get().add(val);
dist.add(val);
}

@Override
public ByteString getValueAndFlush() {
TDigest curVal;
TDigest nextVal = create();
synchronized (this) {
curVal = distRef.getAndSet(nextVal); // reset tdigest
curVal = dist;
dist = nextVal; // reset tdigest
}
ByteBuffer byteBuffer = ByteBuffer.allocate(curVal.smallByteSize());
curVal.asSmallBytes(byteBuffer);
Expand All @@ -75,13 +75,14 @@ public ByteString getValueAndFlush() {


@Override
public long getCount() {
return distRef.get().size();
// This needs to be synchronized because the dist object is not thread-safe
public synchronized long getCount() {
return dist.size();
}

@VisibleForTesting
TDigest tDigest() {
return distRef.get();
return dist;
}

private TDigest create() {
Expand Down