Reputation: 5043
When running a Java jar application, what's the best way to benchmark the CPU and memory usage accurately? I'm currently using VisualVM but I want a plugin or something that I can attach to the pom or project if possible.
Additional: How about in a serverless app like Spring?
Upvotes: 0
Views: 1046
Reputation: 687
You can use Spring Boot Actuator for monitoring. Add spring-boot-starter-actuator dependency, configure application.properties or .yaml file and you can see cpu usage with HTTP request.
Also java provide this structure with MXBean. If you want you can create your own MBean server and show CPU usage on jconsole.
public void exampleCPUUsageWithMXBean() {
long previousJvmProcessCpuTime = 0;
long previousJvmUptime = 0;
com.sun.management.OperatingSystemMXBean prepareOperatingSystemMXBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
java.lang.management.OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
long elapsedProcessCpuTime = prepareOperatingSystemMXBean.getProcessCpuTime() - previousJvmProcessCpuTime;
// elapsed uptime is in milliseconds
long elapsedJvmUptime = runtimeMXBean.getUptime() - previousJvmUptime;
// total jvm uptime on all the available processors
long totalElapsedJvmUptime = elapsedJvmUptime * operatingSystemMXBean.getAvailableProcessors();
float cpuUsage = elapsedProcessCpuTime / (totalElapsedJvmUptime * 10000F);
System.out.println(cpuUsage);
}
Note: I recommend Java Mission Control tool. This tool very useful and showing all details.
Upvotes: 1