Reputation: 1963
I need to run a cpu load monitor on a server. I'd like to create a separate process for that purpose, instead of instrumenting a messy blob of server application code. The question is simple though:
How can I get the system cpu usage (overall and per core, in percentage) using Java?
I've checked OperatingSystemMXBean.getSystemLoadAverage()
, but it gives me the average system cpu load of the last minute, which is too long for me. I need to monitor the load every second (or less). Besides this one give the overall system cpu load.
Finally, is it possible to get the cpu usage of threads that belong to another Java process?
Upvotes: 0
Views: 2184
Reputation: 533492
You need to run mpstat
on Linux in Runtime.exec()
and parse the output. I don't know if there is anything similar on Windows.
$ mpstat -A 10
Linux 3.8.0-27-generic (peter-hex) 08/09/13 _x86_64_ (12 CPU)
21:04:39 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
21:04:49 all 0.27 0.00 0.18 0.00 0.00 0.00 0.00 0.00 99.55
21:04:49 0 0.40 0.00 0.20 0.00 0.00 0.00 0.00 0.00 99.40
21:04:49 1 0.80 0.00 0.50 0.00 0.00 0.00 0.00 0.00 98.70
21:04:49 2 0.50 0.00 0.40 0.00 0.00 0.00 0.00 0.00 99.10
21:04:49 3 0.80 0.00 0.50 0.00 0.00 0.00 0.00 0.00 98.70
21:04:49 4 0.10 0.00 0.20 0.00 0.00 0.00 0.00 0.00 99.70
21:04:49 5 0.70 0.00 0.40 0.00 0.00 0.00 0.00 0.00 98.90
21:04:49 6 0.10 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.90
21:04:49 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
21:04:49 8 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
21:04:49 9 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
21:04:49 10 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
21:04:49 11 0.00 0.00 0.10 0.00 0.00 0.00 0.00 0.00 99.90
is it possible to get the cpu usage of threads that belong to another Java process?
Yes, you can use ps -eLf
and see all threads on the system. This gives you the CPU used since starting. (From which you can calculate utilisation if you want)
Upvotes: 1