Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Timing Java method calls.
// This allows you to call methods wrapped in a timer for profilling.
// I used in a scenario where my abstract class delegated back to concrete implementations, and wanted to be aware of duration.
// Because timer runs in a lambda, it doesn't require any special treatment to see/manipulate current context/scope.
public abstract class AbstractClass{
public final loadDependencies(Map<String, Object> map){
//here we call some methods, they could be anywhere.
ChainResultsSummary results = timing("getChainResultsSummary",() -> getChainResultsSummary(map));
ImmutableChain chain = timing("getImmutableChain",() -> getImmutableChain(map));
List<DeploymentProject> relatedDeployProjects = timing("relatedDeploymentProjects",() -> getRelatedDeploymentProjects(map));
List<DeploymentProjectStatusForResultSummary> relatedDeployResults = timing("relatedDeployResults",() -> getRelatedDeploymentResults(map));
}
public <R> R timing(String name,Supplier<R> operation) {
long start = System.nanoTime();
R result = operation.get();
if(log.isTraceEnabled()){
log.trace( String.format("Execution of %s took %dms\n",name, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.