Execution Statistics.

Recently I needed to find a way of logging the execution statistics of a number of methods in Java classes. The execution statistics included such things as number of invocations per unit of time, the longest and shortest execution time, the accumulated execution time per method etc. This needed to be done in a non-intrusive way – i.e. no direct modification of the code under examination.

This type of orthogonal processing what AspectJ is designed for. A way to use AspectJ for this is now described. The steps are

  1. Setup Maven pom.xml with the required dependencies and the AspectJ build plugin.
  2. Decide on what statistics are to be gathered.
  3. Write a suitable annotation.
  4. Create an AspectJ class to handle the annotation and output the statistics.

Here’s the pom. It uses AspectJ 1.8.10 but referenced as a property for ease of modification.

The next piece of the puzzle is a class to represent the statistics.

This is the annotation. As can be seen it is applied to Methods and retained at runtime. The ‘writePeriod‘ determines how often the accumulated statistics are output.

Next is the Aspect which dictates how AspectJ applies itself.

The key part to this Aspect is the line
@Around("execution(* *(..)) && @annotation(monitor)") which says that for any method, in any package, taking any parameters and with any return type that has the Monitor annotation then execute the following ‘around‘ method. The ‘point.proceed‘ line allows the monitored method to execute but the ‘finally‘ section derives the statistics and creates, if needed, a thread that is run every ‘monitor.writePeriod()‘ seconds and it uses the ‘StatsWriter‘ class to delegate output of the statistics to a ‘StatsSaver‘. All that remains now is to apply the annotation to wherever its is needed. As this is just simple demonstration code the statistics are just printed to the console. In production I used this to write to a MongoDB collection that had a time-to-live on the index.
To try this out I created a rough and ready class with two methods annotated with ‘@Monitor‘.

and the results


Leave a Reply

Your email address will not be published. Required fields are marked *

ˆ Back To Top