mage_dragon mage_dragon - 1 year ago 142
Java Question

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

Answer Source

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 ) {
    Double result = 0.0;
    String[] items = process.replace("  "," ").replace("  "," ").split(" ");
    result = Double.valueOf( items[8].replace(",", ".") );
    return result;


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

EDIT 2: Call

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download