Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use cache for base time unit strings #4487

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
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 @@ -36,6 +36,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.*;
import java.util.stream.Collectors;

import static java.lang.String.format;
import static java.util.Collections.emptyList;
Expand All @@ -59,6 +60,18 @@
*/
public abstract class MeterRegistry {

// @formatter:off
private static final EnumMap<TimeUnit, String> BASE_TIME_UNIT_STRING_CACHE = Arrays.stream(TimeUnit.values())
.collect(
Collectors.toMap(
Function.identity(),
(timeUnit) -> timeUnit.toString().toLowerCase(),
(k, v) -> { throw new IllegalStateException("Duplicate keys should not exist."); },
() -> new EnumMap<>(TimeUnit.class)
)
);
// @formatter:on

protected final Clock clock;

private final Object meterMapLock = new Object();
Expand Down Expand Up @@ -280,7 +293,7 @@ protected String getConventionName(Meter.Id id) {
protected abstract DistributionStatisticConfig defaultHistogramConfig();

private String getBaseTimeUnitStr() {
return getBaseTimeUnit().toString().toLowerCase();
return BASE_TIME_UNIT_STRING_CACHE.get(getBaseTimeUnit());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.micrometer.core.instrument;

import io.micrometer.core.Issue;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
Expand Down Expand Up @@ -205,4 +206,12 @@ void shouldNotLetRegisteringMetersTwice() {
.hasNoCause();
}

@Test
@Issue("#4352")
void baseUnitStringShouldBeCachedAndReturnTheSameInstance() {
Timer timer1 = registry.timer("test.timer1");
Timer timer2 = registry.timer("test.timer2");
assertThat(timer1.getId().getBaseUnit()).isSameAs(timer2.getId().getBaseUnit());
}

}