-1

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

mage_dragon
  • 23
  • 1
  • 5
  • http://stackoverflow.com/questions/74674/how-to-do-i-check-cpu-and-memory-usage-in-java duplicate – user3207081 Jun 20 '15 at 10:07
  • 1
    Not a duplicate. The OP wants to start a process in your code by using `Runtime.getRuntime().exec()` and then check THIS process using the SAME code that started the process... ( may be a separated thread ). I'm just looking for the same. Is NOT a external profiling. Is NOT to check entire CPU VM. – Magno C Sep 29 '15 at 22:07

3 Answers3

0

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 ) )

Magno C
  • 1,922
  • 4
  • 28
  • 53
-2
Runtime.getRuntime().freeMemory()
Runtime.getRuntime().totalMemory()

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

Turbero
  • 116
  • 3
-2

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.

Robert Halter
  • 362
  • 1
  • 9
  • i am not looking to profile the program outside of the program that started it but rather be able to monitor it from the program that started it – mage_dragon Jun 20 '15 at 10:31