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

Optimize Timer instance creation in SimpleTimerCapture #566

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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 @@ -5,12 +5,12 @@ import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Timer
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap

/**
* An abstract class which contains everything is needed to make pretty much any Timer capture.
* Mimicks the Builder pattern and allows captureTime implementation to perform different kinds of
* captures TODO: In order to improve performance, Timer instances can be cached into a thread safe
* Map
* captures
*/
class SimpleTimerCapture<T> : AbstractTimerCapture<T> {
constructor(meterRegistry: MeterRegistry, name: String) : super(meterRegistry, name)
Expand All @@ -19,6 +19,10 @@ class SimpleTimerCapture<T> : AbstractTimerCapture<T> {
timerBuilder: Timer.Builder
) : super(meterRegistry, timerBuilder)

companion object {
private val timerCache = ConcurrentHashMap<Timer.Builder, Timer>()
}

override fun setDescription(description: String): SimpleTimerCapture<T> {
super.setDescription(description)
return this
Expand All @@ -34,15 +38,21 @@ class SimpleTimerCapture<T> : AbstractTimerCapture<T> {
return this
}

private fun getOrCreateTimer(): Timer {
return timerCache.computeIfAbsent(timerBuilder) { builder ->
builder.register(meterRegistry)
}
}

override fun captureTime(f: CompletableFuture<T>): CompletableFuture<T> {
val timer = timerBuilder.register(meterRegistry)
val timer = getOrCreateTimer()
val timerSample = Timer.start(clock)
f.whenComplete { _, _ -> timerSample.stop(timer) }
return f
}

override fun captureTime(f: Callable<T>): T {
val timer = timerBuilder.register(meterRegistry)
val timer = getOrCreateTimer()
val timerSample = Timer.start(clock)
val result = f.call()
timerSample.stop(timer)
Expand Down