Detect the current CPU load status
In Java, directly detecting CPU load status is not as simple as in the operating system command line, because the Java standard library does not directly provide such functions. However, we can indirectly obtain CPU load information through several methods:
(1)Use operating system commands: We can execute specific system commands (such astop
、mpstat
、uptime
etc.) to obtain CPU load information and parse the output of these commands into a format that Java programs can understand. This usually requires use().exec()
method.
(2)Using third-party libraries: Some third-party libraries (such as OSHI, Sigar, etc.) provide the function of obtaining system information (including CPU load).
I will give a use().exec()
Methods and Linux systemmpstat
Example of command. Please note that this example only applies to Linux systems and requires that it is already installed on the system.sysstat
Package (it containsmpstat
Order).
import ; import ; import ; public class CPULoadChecker { public static void main(String[] args) { String command = "mpstat 1 1"; // Run the mpstat command, update once every second, and update once in total try { Process process = ().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; boolean foundCpuLine = false; // Read the output of the command while ((line = ()) != null) { // Skip the title line and other unrelated lines, and only the lines containing CPU information are retained if (("avg-cpu:")) { foundCpuLine = true; ("CPU Load Information:"); (line); // Print CPU load information line break; // Suppose we only care about the first row (load average) } } if (!foundCpuLine) { ("No CPU load information found."); } (); } catch (IOException e) { (); } } }
In this example,mpstat 1 1
The command will runmpstat
And output CPU statistics once and update once every second. However, since we only care about the output once (i.e., load average), we only read and print the first line containing "avg-cpu:".
Note that this example is just a basic starting point and we may need to adjust and expand according to our specific needs. For example, we may need to parsempstat
The output of the command is to obtain more specific CPU load information (such as user space, kernel space, idle time, etc.). Also, if we need to run this code on Windows or other operating systems, we need to replace it with the appropriate system commandsmpstat
。
2. Complete code example
We use().exec()
to execute system commands and parse Linux systemtop
The output of the command to get an approximate percentage of CPU load. However, please note thattop
The output of the command is dynamic and contains multiple lines of text, which may be relatively complex to parse.
Here is a simplified example that usestop -bn1
Commands (non-interactive mode, executed only once) to get CPU usage and try to parse the information therein. However, sincetop
The output format of the command may vary by system configuration and version, so only a basic framework is provided here.
import ; import ; import ; public class CPULoadChecker { public static void main(String[] args) { String os = ("").toLowerCase(); if (("win")) { ("This example is for Linux. For Windows, consider using other methods."); return; } String command = "top -bn1 | grep 'Cpu(s)'"; // Execute the top command and get only the CPU(s) line try { Process process = ().exec(new String[]{"bash", "-c", command}); BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; boolean foundCpuLine = false; // Read the output of the command while ((line = ()) != null) { if (("Cpu(s):")) { foundCpuLine = true; // parse the information of the CPU(s) line, and only the user + system time is obtained as the approximate value of the load String[] parts = ("\\s+"); if ( > 7) { String user = parts[1]; // User space time String system = parts[3]; // Kernel space time double load = (user) + (system); // Suppose we only care about user and system time, and they are all expressed in percentages // Note: This is not the real CPU load, it is just the sum of user and system time ("Approximate CPU Load: %.2f%% (User: %.2f%%, System: %.2f%%)%n", load, (user), (system)); } break; } } if (!foundCpuLine) { ("No CPU load information found."); } (); } catch (IOException e) { (); } } }
Notice:
(1) This example assumes that our system supportsbash
andtop
command, andtop
The output format of the command matches the one described in the example.
(2) This method is just an approximation because it only considers user and system time, and does not consider waiting time, idle time, etc.
(3) If we need more accurate CPU load information, it is recommended to use special system monitoring tools or libraries, such asOSHI
、Sigar
wait.
(4) On Windows systems, we need to use different commands and parsing logic, becausetop
The command does not exist on Windows. We can consider usingwmic
Commands or other Windows-specific methods.
Java in the system detects the current CPU load status
In Windows systems, Java usually requires the use of some specific commands or third-party libraries to detect the current CPU load state, because the Java standard library does not directly provide such functions. Here are a few common methods:
3.1 Usewmic
Order
We can executewmic
Command (Windows Management Instrumentation Command-line) to obtain CPU usage. Here is a sample code snippet showing how to use it().exec()
Method to executewmic
Command and parse its output:
import ; import ; import ; public class CPULoadCheckerWindows { public static void main(String[] args) { String command = "wmic cpu get loadpercentage /value"; try { Process process = ().exec(new String[]{"", "/c", command}); BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; while ((line = ()) != null) { // Skip the title line and other unrelated lines if (("LoadPercentage=")) { // parse CPU load percentage String[] parts = ("="); if ( > 1) { String cpuLoad = parts[1].trim(); // Remove the percent sign and convert it to an integer (if needed) int load = (("%", "")); ("CPU Load: " + load + "%"); } break; // Suppose we only care about the first line } } (); } catch (IOException e) { (); } } }
3.2 Using third-party libraries
We can also use third-party libraries to obtain CPU load information. These libraries usually provide cross-platform support, making the code easier to maintain and scale. For example, we can useOSHI
The (Open System and Hardware Information) library is used to obtain CPU usage.
Here is an example of using the OSHI library to get CPU load:
First, we need to add dependencies of the OSHI library to the project. If we use Maven, we canAdd the following dependencies to the file:
<dependency> <groupId>oshi-project</groupId> <artifactId>oshi-core</artifactId> <version>Our version number</version> </dependency>
We can then write the following code to get the CPU load:
import ; import ; public class CPULoadCheckerWithOshi { public static void main(String[] args) { SystemInfo si = new SystemInfo(); CentralProcessor cpu = ().getProcessor(); // Get the CPU's recent load (the load of the past 1 second, 5 seconds and 15 seconds) double[] loadAverage = (1, 5, 15); ("CPU Load (1s): " + loadAverage[0] * 100 + "%"); ("CPU Load (5s): " + loadAverage[1] * 100 + "%"); ("CPU Load (15s): " + loadAverage[2] * 100 + "%"); } }
Please note that we need toOur version number
Replace with the latest version number of the OSHI library. Additionally, since the OSHI library uses local libraries (JNI) to get system information, we may need to make sure that the correct local library files are included in the runtime environment.
This is the end of this article about Java's method of detecting the current CPU load status. For more related content on Java CPU load status, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!