SoFunction
Updated on 2025-04-11

Implementation method of using Java to view process memory usage

1. Project background and introduction

In system monitoring and performance tuning, understanding the memory usage of each process is a very important part. By checking process memory usage, developers and operation and maintenance personnel can promptly detect abnormal processes, resource bottlenecks and memory leak problems. Although the operating system itself usually provides corresponding commands or tools (such as tasklist for Windows, ps for Linux, etc.), implementing a cross-platform process memory monitoring tool in Java applications can easily integrate monitoring results into the system management platform or application.

This project aims to write a simple program in Java that calls the operating system commands to obtain the memory usage of each process in the system and output the results to the console. Through this project, readers can learn how to use Java's ProcessBuilder to call external commands, how to parse command output, and master some cross-platform judgment skills.

2. Related knowledge

2.1 Operating system commands

The commands for viewing process memory usage are different on different platforms:

  • Windows: Commonly used commands aretasklist, can list all processes and their memory usage.
  • Linux/Unix/Mac: Can be usedps auxCommand to view detailed information of each process, including data such as memory usage percentage.

2.2 ProcessBuilder and Process

Provided by JavaProcessBuilderThe class can be used to start an external process, execute operating system commands, and return theProcessThe object obtains the output information of the process. Using this mechanism, we can call it in Java programstasklistorps auxCommand to obtain process information.

2.3 Cross-platform judgment

By calling(""), we can get the name of the current operating system. Judging the operating system type based on the returned result, and thus selecting the appropriate command to call it.

3. Project implementation ideas

The main ideas for this project to view the process memory usage are as follows:

  1. Determine the operating system type
    use("")Determine whether the current system is Windows or Linux/Unix/Mac, and then select the appropriate command.

  2. Construct and start external processes
    UtilizeProcessBuilderConstruct commands (such as those under Windowscmd /c tasklist, under Linux/Macbash -c "ps aux") and start the process.

  3. Read and output command execution results
    Read content from the standard output of an external process and display the results in the console. The results can also be further parsed and processed (such as extracting information such as memory usage).

  4. Handle exceptions and ensure resource shutdown
    Catch and handle possible I/O and interrupt exceptions to ensure that the program runs robustly.

4. Complete code implementation

Below is a complete Java code example, using ProcessBuilder to call system commands to obtain process information and output the results. The code contains detailed Chinese comments to facilitate understanding of the implementation principle of each step.

import ;
import ;
import ;
import ;
 
/**
  * The ProcessMemoryUsage class implements a simple Java program to view the memory usage of each process in the system.
  * The program selects the appropriate command based on the current operating system (use tasklist for Windows, use ps aux for Linux/Mac).
  * Call external commands through ProcessBuilder and print the command output to the console.
  */
public class ProcessMemoryUsage {
 
    public static void main(String[] args) {
        // Get the current operating system name and convert it to lowercase        String os = ("").toLowerCase();
        ProcessBuilder processBuilder;
 
        //Construct different commands according to the operating system type        if (("win")) {
            // Under Windows system, use the "cmd /c tasklist" command to obtain process information            processBuilder = new ProcessBuilder("cmd", "/c", "tasklist");
        } else if (("nix") || ("nux") || ("mac")) {
            // Under Linux/Unix/Mac system, use the "bash -c ps aux" command to obtain process information            processBuilder = new ProcessBuilder("bash", "-c", "ps aux");
        } else {
            ("The current operating system does not support this program:" + os);
            return;
        }
 
        try {
            // Start external processes            Process process = ();
 
            // Get the standard output stream of external processes            InputStream inputStream = ();
            // Use BufferedReader to read the output content            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
 
            String line;
            ("Process memory usage:");
            // Read the output line by line and print to the console            while ((line = ()) != null) {
                (line);
            }
 
            // Wait for the external process to complete execution            int exitCode = ();
            ("The command has been executed, the exit code is:" + exitCode);
 
        } catch (IOException | InterruptedException e) {
            //Catch exceptions and print error stack information            ("An error occurred while executing the command:" + ());
            ();
        }
    }
}

5. Code interpretation

5.1 Operating system judgment

  • Get the operating system name
    use("").toLowerCase()Get the current system name and convert it to lowercase for easier subsequent judgment.

  • Construct command
    Judging by the operating system:

    • If the system name contains "win", it is considered Windows and use"cmd", "/c", "tasklist"As a command.
    • If the system name contains "nix", "nux", or "mac", use"bash", "-c", "ps aux"Command obtains process information.
    • If the current system is not supported, the prompt message is output and the program is exited.

5.2 Starting external processes and reading output

  • ProcessBuilder starts the process
    pass()Start the process corresponding to the external command.

  • Read the output
    Get the standard output stream of the process and useBufferedReaderPress line to read the output content and print to the console. This allows you to intuitively view the memory usage, PID, process name and other information of each process.

  • Wait for the process to end
    Call()The method waits for the external process to complete execution and obtains the exit code to facilitate understanding of the command execution status.

5.3 Exception handling

  • Use try-catch to capture in the programIOExceptionandInterruptedExceptionException and print detailed error information to ensure that the program does not crash when an exception occurs, and to facilitate debugging.

6. Project Summary and Prospect

This project realizes the function of viewing the memory usage of each process in the system through Java. The main gains and experiences include:

  1. Master the basic methods of calling external commands
    Start external processes and read output through ProcessBuilder, allowing Java programs to call the command line tools provided by the operating system to realize cross-platform system monitoring.

  2. Cross-platform processing skills
    By judging the operating system type and selecting different commands to execute, the compatibility between Windows and Linux/Mac platforms is achieved.

  3. Resource management and exception handling
    Rationally handle process output streams, wait for the process to end, and catch exceptions to ensure that the program runs robustly.

  4. Expansion and optimization direction

    • Results analysis and presentation: You can further parse the command output, extract the memory usage data of each process, and format it to display, such as generating a chart or sorting it to display the processes with the largest memory usage.
    • Graphic interface integration: Combined with Java Swing or JavaFX, process memory usage data is displayed on a graphical interface to build a real-time monitoring tool.
    • Timely refresh: Implement the timed refresh function, periodically update system process information, and realize dynamic monitoring.

In short, this project shows how to use Java to call external commands to view system process information, and provides a foundation for subsequent construction of more complex system monitoring tools. I hope this blog post can provide you with valuable reference and inspiration in Java system monitoring and performance tuning.

Through this blog post, you can fully understand how to use Java implementation to view process memory usage, from theoretical basis to code implementation, to detailed code interpretation and project summary. I hope this article can help and inspire you and your readers in the exploration of Java system monitoring and performance analysis.

The above is the detailed content of the implementation method of using Java to view process memory usage. For more information about Java to view process memory, please pay attention to my other related articles!