Skip to content

Commit

Permalink
Ignore noop children in CompositeMeter
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatan-ivanov committed Jan 28, 2024
1 parent b9b2f0d commit 5cb55eb
Showing 1 changed file with 25 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@
import io.micrometer.core.instrument.AbstractMeter;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.noop.NoopMeter;

import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

abstract class AbstractCompositeMeter<T extends Meter> extends AbstractMeter implements CompositeMeter {

private final AtomicBoolean childrenGuard = new AtomicBoolean();

private Map<MeterRegistry, T> children = Collections.emptyMap();
private State state = new State(Collections.emptyMap());

@Nullable
private volatile T noopMeter;
Expand All @@ -45,13 +45,12 @@ abstract class AbstractCompositeMeter<T extends Meter> extends AbstractMeter imp
abstract T registerNewMeter(MeterRegistry registry);

final Iterable<T> getChildren() {
return children.values();
return state.children.values();
}

T firstChild() {
final Iterator<T> i = children.values().iterator();
if (i.hasNext())
return i.next();
if (state.firstNonNoopChild != null)
return state.firstNonNoopChild;

// There are no child meters. Return a lazily instantiated no-op meter.
final T noopMeter = this.noopMeter;
Expand All @@ -73,9 +72,9 @@ public final void add(MeterRegistry registry) {
for (;;) {
if (childrenGuard.compareAndSet(false, true)) {
try {
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(state.children);
newChildren.put(registry, newMeter);
this.children = newChildren;
this.state = new State(newChildren);
break;
}
finally {
Expand All @@ -95,9 +94,9 @@ public final void remove(MeterRegistry registry) {
for (;;) {
if (childrenGuard.compareAndSet(false, true)) {
try {
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(state.children);
newChildren.remove(registry);
this.children = newChildren;
this.state = new State(newChildren);
break;
}
finally {
Expand All @@ -107,4 +106,20 @@ public final void remove(MeterRegistry registry) {
}
}

private class State {

private final Map<MeterRegistry, T> children;

@Nullable
private final T firstNonNoopChild;

State(final Map<MeterRegistry, T> children) {
this.children = children;
firstNonNoopChild = children.values()
.stream()
.filter(child -> !(child instanceof NoopMeter))
.findFirst()
.orElse(null);
}
}
}

0 comments on commit 5cb55eb

Please sign in to comment.