简体   繁体   中英

how to read the memory and cpu usage of a process started by java

i am starting a java process using

Runtime.getRuntime().exec("java -jar javaprogarm.jar");

i want to monitor the process that is started ram and CPU usage is there a way to do this in a cross platform manner?

edit: to clarify i am not looking for the total system cpu and ram usage but rather the usage of that one process that i am starting. the question that was considered a duplicate is looking for the system cpu and ram not just a single process

Try this:

1) To hold all your running processes:

private List<String> processes = new ArrayList<String>();

2) To get all java running processes:

private void getRunningProcesses() throws Exception {
    Process process = Runtime.getRuntime().exec("top -b -n1 -c");
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ( (line = br.readLine()) != null) {
        if( line.contains("java") ) processes.add( line );  
    }   
}

3) To get an information line from PID ( getRunningProcesses() first ):

private String getByPid( int pid ) {
    for ( String line : processes ) {
        if ( line.startsWith( String.valueOf( pid ) ) ) {
            return line;
        }
    }
    return "";
}

4) Now you have a line with all "top" information from that PID. Get the CPU %:

private Double getCpuFromProcess( String process ) {
    //PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
    Double result = 0.0;
    String[] items = process.replace("  "," ").replace("  "," ").split(" ");
    result = Double.valueOf( items[8].replace(",", ".") );
    return result;
}

Done.

EDIT: Don't forget to clear processes list before each call.

EDIT 2: Call

getRunningProcesses() , then getCpuFromProcess( getByPid( the_pid ) )

Runtime.getRuntime().freeMemory()
Runtime.getRuntime().totalMemory()

Maybe those methods will help you. The returned long values are measured by bytes.

Use the jvisualvm Tool.
It is located in your Java JDK Installation in the bin Folder.
It is a Graphical Tool, wher you can select a running Java VM.
In the Monitor Tab you can see CPU and Memory(Heap) usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM