For a particular segment of Java code, I\'d like to measure:
We can measure the cpu and memory used during a specific invoked method by collecting the cpu and memory metrics during its execution.
Of course if other concurrent threads for other methods consumes memory and cpu during its execution, you are stuck. So it is a valid approach while you are able to execute a method in a isolated way.
For the CPU you can get its current value :
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class);
double processCpuLoad = osBean.getProcessCpuLoad();
For the memory you can do that :
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
int currentHeapUsedInMo = (int) (memoryMXBean.getHeapMemoryUsage().getUsed() / 1_000_000);
About the memory measure, waiting for a major collect before executing the method improves its reliability.
For example something like that may help :
import com.google.common.testing.GcFinalization;
GcFinalization.awaitFullGc();
foo.execute(); // method to execute
GcFinalization comes from the Guava test library.
All that has few overheads. So the idea is collecting metrics (for example each second) for each invoked method you want to monitor and when the method returned, compute the max/average or any useful information for them.
I would favor AOP to do that.
Spring AOP is a simple and good way to create aspects and set pointcuts for them but you can also do it with AspectJ if you need some particular things in terms of AOP features.