How to get Linux Process Cpu and Memory Usage in Java programmatically
Author: Veeresh Rudrappa. Date: Sep 14, 2012
This is a no brainer approach for getting CPU and Memory usage of the running processes under Linux. All we do is execute Linux shell commands programmatically in Java and extract its output. I had to use this when I was developing a monitoring software for Linux. Of course there are lots of libraries available to accomplish this and I ended up using them as well to complete my project. One such library is Sigar Api. Well, if you are forced to do it the crude way, you can use code below. However, it also is a good introduction for executing Linux commands from Java if you haven't done it already.
package com.project.extract; import java.io.BufferedReader; import java.io.InputStreamReader; public class GetCpuInfo { public static void main(String [] args) { try { Process P = Runtime.getRuntime().exec("top -b -n 1"); P.waitFor(); BufferedReader StdInput = new BufferedReader(new InputStreamReader(P.getInputStream())); String TopS =""; int i=0; while((TopS= StdInput.readLine())!=null) { if(i==2) System.out.println(TopS); if(i>6 && i<17) { TopS=TopS.replaceAll(" ", " "); TopS=TopS.replaceAll(" ", " "); TopS=TopS.replaceAll(" ", " "); String[] tokens1= TopS.split(" "); int j=8; if(tokens1[0].isEmpty()) j=j+1; String ProcCpuUtil = new String(tokens1[j]); j++; Float ProcMemUtil = Float.parseFloat(tokens1[j]); j = j+2; String ProcName = new String(tokens1[j]); System.out.println(ProcName+"\t"+ProcCpuUtil+"\t"+ProcMemUtil); } i++; } }catch(Exception e) { } } }Note that top is a continuous process and doesn't terminate. So you would have to take a snapshot of the process with top -b -n 1.
Now that you know how to execute Linux commands from with in Java program, you can try other commands to extract useful system information.
Process Proc = Runtime.getRuntime().exec("cat /proc/cpuinfo"); Proc.waitFor(); BufferedReader Pinput = new BufferedReader(new InputStreamReader(Proc.getInputStream())); String Flags = ""; while((Flags= Pinput.readLine())!=null) { // Do your stuff here and extract the necessary information }