1

I want to monitor system metrics at my application. I use Spring Boot Actuator but it doesn't have any metrics for CPU usage. I know that such metrics at Spring Boot Actuator retrieve from here:

OperatingSystemMXBean

It has methods like:

getSystemLoadAverage
getAvailableProcessors

There is another class:

MemoryUsage

at which you can retrieve such metrics:

getUsed
getCommitted

However I could not see any metrics for CPU Usage of the Java application at java.lang.management. How can I retrieve it?

kamaci
  • 72,915
  • 69
  • 228
  • 366
  • [`com.sun.management.OperatingSystemMXBean.getSystemCpuLoad()`](http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad())? – Andrew Li Oct 30 '16 at 15:03
  • @AndrewLi Does SystemCpuLoad equals to getSystemLoadAverage/getAvailableProcessors ? – kamaci Oct 30 '16 at 15:21
  • No. `getSystemCpuLoad` returns recent CPU usage of the whole system. See the duplicate – Andrew Li Oct 30 '16 at 15:23
  • Actually, I need the CPU usage of the current Java application as like heap usage. That's why I need a different solution than the duplicate. – kamaci Oct 30 '16 at 15:55
  • `getProcessCpuLoad()` – Andrew Li Oct 30 '16 at 15:56
  • I couldn't instantiate com.sun.management.OperatingSystemMXBean – kamaci Oct 30 '16 at 16:32
  • `com.sun.management.OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);` then use methods – Andrew Li Oct 30 '16 at 16:42

2 Answers2

1

You're talking about OperatingSystemMXBean class of java.lang.management package. There is the same name class in the com.sun.management package. In this class there are few methods abouts cpu info:

double  getProcessCpuLoad()
long    getProcessCpuTime()
double  getSystemCpuLoad()

This is the code in order to access the bean and retrieve cpu load info:

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
System.out.println(bean.getProcessCpuLoad());

Note that the cast is necessary because the class you need is in java.sun.management package not in java.lang.management. You could encounter some problems about access restriction if you use eclipse, if this happens you can easily fix it in this way.

Community
  • 1
  • 1
user6904265
  • 1,938
  • 1
  • 16
  • 21
0

Just suggestion, I think we should NOT use the measuring inside our application, just because beside the workload of our application, there the workload of the measuring, so the result is not exactly anymore
Jconsole or Visualvm are the great external tools you can take eyes in this case. Not only springboot, but also you can measure all of java application types.

nhthai
  • 198
  • 2
  • 10