Skip to content

Commit

Permalink
Enforce start happens-before stop
Browse files Browse the repository at this point in the history
Closes gh-13133
  • Loading branch information
jzheaux committed May 8, 2023
1 parent 0b6e84b commit 5d903b5
Showing 1 changed file with 28 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.micrometer.common.KeyValue;
import io.micrometer.common.KeyValues;
Expand Down Expand Up @@ -382,6 +384,8 @@ private static final class ObservationReference {

private static final ObservationReference NOOP = new ObservationReference(Observation.NOOP);

private final Lock lock = new ReentrantLock();

private final AtomicInteger state = new AtomicInteger(0);

private final Observation observation;
Expand All @@ -391,20 +395,38 @@ private ObservationReference(Observation observation) {
}

private void start() {
if (this.state.compareAndSet(0, 1)) {
this.observation.start();
try {
this.lock.lock();
if (this.state.compareAndSet(0, 1)) {
this.observation.start();
}
}
finally {
this.lock.unlock();
}
}

private void error(Throwable ex) {
if (this.state.get() == 1) {
this.observation.error(ex);
try {
this.lock.lock();
if (this.state.get() == 1) {
this.observation.error(ex);
}
}
finally {
this.lock.unlock();
}
}

private void stop() {
if (this.state.compareAndSet(1, 2)) {
this.observation.stop();
try {
this.lock.lock();
if (this.state.compareAndSet(1, 2)) {
this.observation.stop();
}
}
finally {
this.lock.unlock();
}
}

Expand Down

0 comments on commit 5d903b5

Please sign in to comment.