Skip to content

Commit a0f5c74

Browse files
committed
Use IdentityHashMap for consistent JIT optimization in AbstractCompositeMeter
Replace Collections.emptyMap() with new IdentityHashMap<>() to maintain consistent map implementation type throughout the object's lifecycle, enabling JVM scalar replacement optimization and reducing iterator allocation overhead. Fixes gh-6811 Signed-off-by: David Mollitor <[email protected]>
1 parent 65301f0 commit a0f5c74

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,20 @@
2020
import io.micrometer.core.instrument.MeterRegistry;
2121
import org.jspecify.annotations.Nullable;
2222

23-
import java.util.Collections;
2423
import java.util.IdentityHashMap;
2524
import java.util.Iterator;
26-
import java.util.Map;
2725
import java.util.concurrent.atomic.AtomicBoolean;
2826

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

29+
private static final IdentityHashMap<MeterRegistry, Meter> EMPTY_CHILDREN = new IdentityHashMap<>(0);
30+
3131
private final AtomicBoolean childrenGuard = new AtomicBoolean();
3232

33-
private Map<MeterRegistry, T> children = Collections.emptyMap();
33+
// Enforcing type of Map to explicitly be constrained to one type may help JIT
34+
// optimizations.
35+
@SuppressWarnings("unchecked")
36+
private IdentityHashMap<MeterRegistry, T> children = (IdentityHashMap<MeterRegistry, T>) EMPTY_CHILDREN;
3437

3538
private volatile @Nullable T noopMeter;
3639

@@ -72,7 +75,7 @@ public final void add(MeterRegistry registry) {
7275
for (;;) {
7376
if (childrenGuard.compareAndSet(false, true)) {
7477
try {
75-
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
78+
IdentityHashMap<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
7679
newChildren.put(registry, newMeter);
7780
this.children = newChildren;
7881
break;
@@ -95,7 +98,7 @@ public final void remove(MeterRegistry registry) {
9598
for (;;) {
9699
if (childrenGuard.compareAndSet(false, true)) {
97100
try {
98-
Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
101+
IdentityHashMap<MeterRegistry, T> newChildren = new IdentityHashMap<>(children);
99102
newChildren.remove(registry);
100103
this.children = newChildren;
101104
break;

0 commit comments

Comments
 (0)