I want to track how long an async process takes.
My general approach for synchronous processes is to record the current time, run the process, and finally calculate and record the difference. I use an AutoCloseable Timer object to do this. But I'm not sure if this will work for futures.
class MyTimer implements AutoCloseable {
private final long startTime;
MyTimer(...) {
startTime = clock.millis();
}
@Override
public void close() {
recorder.record(clock.millis() - startTime);
}
}
This doesn't work obviously because I'm only recording the time it takes to construct the future, not actually complete it fully
public ListenableFuture doSomethingAsync() {
try(MyTimer timer = new MyTimer()) {
return thirdPartyLib.readDatabase();
}
}
I'm not sure if this will work though
public ListenableFuture doSomethingAsync() {
MyTimer timer = new MyTimer();
ListenableFuture future = thirdPartyLib.readDatabase();
future.addListener(() -> timer.close(), listeningExecutorService);
return future;
}
What I'm afraid of is that when the method exits, the method-scoped Timer is garbage collected so when the listener lambda executes, timer is in a unpredictable state.
But I'm not sure if the fact that the lambda holds a reference to timer prevents it from going away once the method exists.
What's the right way to time the future?
Edit Edit to make clear that readDatabase() is not my task code but 3rd party library I don't control. Also, timer is a custom class I built.