Is there a way to get the current cpu load under Java without using the JNI?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
On linux you could just read the file /proc/loadavg, where the first three values represent the load averages. For Windows you probably have to stick to JNI.
Under Linux you could use Runtime.exec() to execute “uptime” and evaluate the output. I don’t there’s a better way under Linux, and I don’t think there’s an equally “convenient” way under Windows.
Use the
ManagementFactory
to get anOperatingSystemMXBean
and callgetSystemLoadAverage()
on it.This does involve JNI but there is a GPL library from Hyperic called Sigar that provides this information for all the major platforms, as well as a bunch of other OS-dependent stats like disk usage. It's worked great for us.
getSystemLoadAverage() gives you value over 1 minute of time (refreshes every second) and gives this value for overall operating system. More realtime overview should be done by monitoring each thread separately. Important is also notice the monitoring refresh interval - more often you check the value, more precice it is in given moment and if you do it every millisecond, it is typically 0 or 100 (or more depending how many CPU's is there). But if we allow timeframe (for example 1 second), we get avarage over this period of time and we get more informative result. Also, it is important to notice, that it is highly unlikely, that only one thread occupies more than one CPU (core).
Following implementation allows to use 3 methods:
getUsageByThread(Thread t) - Total load by specified thread
If you're using the JRockit JVM you could use JMAPI. It works for JDK 1.4, 1.5 and 1.6.