Skip to content

Commit

Permalink
Use cache for base time unit strings (#4487)
Browse files Browse the repository at this point in the history
* Use cache for base time unit strings

Closes gh-4352

* Polish "Use cache for base time unit strings"

---------

Co-authored-by: Jonatan Ivanov <jonatan.ivanov@gmail.com>
  • Loading branch information
izeye and jonatan-ivanov authored Dec 11, 2023
1 parent 29e437b commit 0fb75c1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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());
}

}

0 comments on commit 0fb75c1

Please sign in to comment.