Skip to content

Commit

Permalink
No volatile variables
Browse files Browse the repository at this point in the history
  • Loading branch information
jack-berg committed Nov 10, 2023
1 parent 55b845a commit 60c2b43
Showing 1 changed file with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
Expand All @@ -49,7 +50,9 @@ public final class DefaultSynchronousMetricStorage<T extends PointData, U extend
private final MetricDescriptor metricDescriptor;
private final AggregationTemporality aggregationTemporality;
private final Aggregator<T, U> aggregator;
private volatile AggregatorHolder<T, U> aggregatorHolder = new AggregatorHolder<>();
private final AtomicInteger collectCount = new AtomicInteger();
private final AggregatorHolder<T, U> holder1 = new AggregatorHolder<>();
private final AggregatorHolder<T, U> holder2 = new AggregatorHolder<>();
private final AttributesProcessor attributesProcessor;

/**
Expand Down Expand Up @@ -85,6 +88,7 @@ Queue<AggregatorHandle<T, U>> getAggregatorHandlePool() {

@Override
public void recordLong(long value, Attributes attributes, Context context) {
AggregatorHolder<T, U> aggregatorHolder = collectCount.get() % 2 == 0 ? holder1 : holder2;
Lock readLock = aggregatorHolder.lock.readLock();
readLock.lock();
try {
Expand All @@ -108,6 +112,7 @@ public void recordDouble(double value, Attributes attributes, Context context) {
+ ". Dropping measurement.");
return;
}
AggregatorHolder<T, U> aggregatorHolder = collectCount.get() % 2 == 0 ? holder1 : holder2;
Lock readLock = aggregatorHolder.lock.readLock();
readLock.lock();
try {
Expand Down Expand Up @@ -167,8 +172,7 @@ public MetricData collect(

ConcurrentHashMap<Attributes, AggregatorHandle<T, U>> aggregatorHandles;
if (reset) {
AggregatorHolder<T, U> holder = this.aggregatorHolder;
this.aggregatorHolder = new AggregatorHolder<>();
AggregatorHolder<T, U> holder = collectCount.getAndIncrement() % 2 == 0 ? holder1 : holder2;
Lock writeLock = holder.lock.writeLock();
writeLock.lock();
try {
Expand All @@ -177,7 +181,7 @@ public MetricData collect(
writeLock.unlock();
}
} else {
aggregatorHandles = this.aggregatorHolder.aggregatorHandles;
aggregatorHandles = holder1.aggregatorHandles;
}

// Grab aggregated points.
Expand All @@ -201,6 +205,10 @@ public MetricData collect(
aggregatorHandlePool.poll();
}

if (reset) {
aggregatorHandles.clear();
}

if (points.isEmpty()) {
return EmptyMetricData.getInstance();
}
Expand Down

0 comments on commit 60c2b43

Please sign in to comment.