support Autocloseable with Timer
See original GitHub issueI’m migrating from the prometheus API and changing the Timer code is quite cumbersome. In Prometheus, I could do the following:
public void myTimedMethod() throws CheckedException {
try(timer.startTimer()) {
methodThatThrowsCheckedException();
}
}
However, Micrometer’s Timer objects are not Autocloseable. The methods I see in Timer, record()
and recordCallable()
, take lambda functions, but lambda functions do not allow throwing checked exceptions, leading to lots of annoying boilerplate (I’m following section 3.1 from this Baeldung article). recordCallable()
explicitly declares the caller as throwing Exception
, which is also not good because now the code I write has to handle the general Exception
instead of my specific exception class.
Because I really prefer the autocloseable usage, I ended up writing a little wrapper class:
public static class TimerCloser implements AutoCloseable {
private final Timer timer;
private final Timer.Sample sample;
public TimerCloser(Timer t) {
this.timer = t;
this.sample = Timer.start();
}
public void close(){
sample.stop(timer);
}
}
And I use it like this:
try(TimerCloser closer = new TimerCloser(myTimer)) {...
It would be much easier for me if the I could call myTimer.start()
and that would return an autocloseable class similar to Timer.Sample, and then the close()
method would call Timer.Sample.stop()
. We can’t just change Timer.Sample to be autocloseable, unfortunately, because it contains no reference to the timer metric to write the results to.
Issue Analytics
- State:
- Created 4 years ago
- Comments:10 (6 by maintainers)
Top GitHub Comments
I’ve since become more educated, specifically from https://vimeo.com/181925278 and testing with JITWatch. If your AutoCloseableObject is final and stays simple, the VM will not even allocate an extra object, so there is literally no GC penalty at all. The impact is the same as if the AutoCloseableObject fields were defined as local fields in your method.
So fascinating, I’ve never heard this! Thanks for taking the time to explain. I guess let’s figure out a way to get this done?