`

利用java程序实现获取计算机cpu利用率和内存状况

 
阅读更多

很多时候需要监控我们的程序,以随时知道程序运行状况、预警等


以下是网上某博客代码,特点是通过window和linux命令获得CPU使用率。

 

Java代码

利用java程序实现获取计算机cpu利用率和内存使用信息。

创建一个Bean用来存贮要得到的信

 

Java代码  收藏代码
  1. /** 
  2.  * @author yans 
  3.  * @date 2011-10-6 下午11:23:45 
  4.  * @description 
  5.  */  
  6. public class MonitorInfoBean {  
  7.     /** 可使用内存. */  
  8.     private long totalMemory;  
  9.   
  10.     /** 剩余内存. */  
  11.     private long freeMemory;  
  12.   
  13.     /** 最大可使用内存. */  
  14.     private long maxMemory;  
  15.   
  16.     /** 操作系统. */  
  17.     private String osName;  
  18.   
  19.     /** 总的物理内存. */  
  20.     private long totalMemorySize;  
  21.   
  22.     /** 剩余的物理内存. */  
  23.     private long freePhysicalMemorySize;  
  24.   
  25.     /** 已使用的物理内存. */  
  26.     private long usedMemory;  
  27.   
  28.     /** 线程总数. */  
  29.     private int totalThread;  
  30.   
  31.     /** cpu使用率. */  
  32.     private double cpuRatio;  
  33.   
  34.     public long getFreeMemory() {  
  35.         return freeMemory;  
  36.     }  
  37.   
  38.     public void setFreeMemory(long freeMemory) {  
  39.         this.freeMemory = freeMemory;  
  40.     }  
  41.   
  42.     public long getFreePhysicalMemorySize() {  
  43.         return freePhysicalMemorySize;  
  44.     }  
  45.   
  46.     public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {  
  47.         this.freePhysicalMemorySize = freePhysicalMemorySize;  
  48.     }  
  49.   
  50.     public long getMaxMemory() {  
  51.         return maxMemory;  
  52.     }  
  53.   
  54.     public void setMaxMemory(long maxMemory) {  
  55.         this.maxMemory = maxMemory;  
  56.     }  
  57.   
  58.     public String getOsName() {  
  59.         return osName;  
  60.     }  
  61.   
  62.     public void setOsName(String osName) {  
  63.         this.osName = osName;  
  64.     }  
  65.   
  66.     public long getTotalMemory() {  
  67.         return totalMemory;  
  68.     }  
  69.   
  70.     public void setTotalMemory(long totalMemory) {  
  71.         this.totalMemory = totalMemory;  
  72.     }  
  73.   
  74.     public long getTotalMemorySize() {  
  75.         return totalMemorySize;  
  76.     }  
  77.   
  78.     public void setTotalMemorySize(long totalMemorySize) {  
  79.         this.totalMemorySize = totalMemorySize;  
  80.     }  
  81.   
  82.     public int getTotalThread() {  
  83.         return totalThread;  
  84.     }  
  85.   
  86.     public void setTotalThread(int totalThread) {  
  87.         this.totalThread = totalThread;  
  88.     }  
  89.   
  90.     public long getUsedMemory() {  
  91.         return usedMemory;  
  92.     }  
  93.   
  94.     public void setUsedMemory(long usedMemory) {  
  95.         this.usedMemory = usedMemory;  
  96.     }  
  97.   
  98.     public double getCpuRatio() {  
  99.         return cpuRatio;  
  100.     }  
  101.   
  102.     public void setCpuRatio(double cpuRatio) {  
  103.         this.cpuRatio = cpuRatio;  
  104.     }  
  105.   
  106. }  

 之后,建立bean的接口

Java代码  收藏代码
  1. /** 
  2.  * @author yans 
  3.  * @date 2011-10-6 下午11:24:31 
  4.  * @description 
  5.  */  
  6. public interface IMonitorService {  
  7.     public MonitorInfoBean getMonitorInfoBean() throws Exception;  
  8. }  

 然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。

 

 

Java代码  收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.LineNumberReader;  
  7. import java.lang.management.ManagementFactory;  
  8. import java.util.StringTokenizer;  
  9.   
  10. import com.sun.management.OperatingSystemMXBean;  
  11.   
  12. /** 
  13.  * @author yans 
  14.  * @date 2011-10-6 下午11:24:58 
  15.  * @description 获取系统信息的业务逻辑实现类. 
  16.  */  
  17. public class MonitorServiceImpl implements IMonitorService {  
  18.   
  19.     private static final int CPUTIME = 30;  
  20.   
  21.     private static final int PERCENT = 100;  
  22.   
  23.     private static final int FAULTLENGTH = 10;  
  24.   
  25.     private static final File versionFile = new File("/proc/version");  
  26.     private static String linuxVersion = null;  
  27.   
  28.     /** 
  29.      * 获得当前的监控对象. 
  30.      *  
  31.      * @return 返回构造好的监控对象 
  32.      * @throws Exception 
  33.      * @author yans 
  34.      */  
  35.     public MonitorInfoBean getMonitorInfoBean() throws Exception {  
  36.         int kb = 1024;  
  37.   
  38.         // 可使用内存  
  39.         long totalMemory = Runtime.getRuntime().totalMemory() / kb;  
  40.         // 剩余内存  
  41.         long freeMemory = Runtime.getRuntime().freeMemory() / kb;  
  42.         // 最大可使用内存  
  43.         long maxMemory = Runtime.getRuntime().maxMemory() / kb;  
  44.   
  45.         OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory  
  46.                 .getOperatingSystemMXBean();  
  47.   
  48.         // 操作系统  
  49.         String osName = System.getProperty("os.name");  
  50.         // 总的物理内存  
  51.         long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;  
  52.         // 剩余的物理内存  
  53.         long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;  
  54.         // 已使用的物理内存  
  55.         long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb  
  56.                 .getFreePhysicalMemorySize())  
  57.                 / kb;  
  58.   
  59.         // 获得线程总数  
  60.         ThreadGroup parentThread;  
  61.         for (parentThread = Thread.currentThread().getThreadGroup(); parentThread  
  62.                 .getParent() != null; parentThread = parentThread.getParent())  
  63.             ;  
  64.         int totalThread = parentThread.activeCount();  
  65.   
  66.         double cpuRatio = 0;  
  67.         if (osName.toLowerCase().startsWith("windows")) {  
  68.             cpuRatio = this.getCpuRatioForWindows();  
  69.         } else {  
  70.             cpuRatio = this.getCpuRateForLinux();  
  71.         }  
  72.   
  73.         // 构造返回对象  
  74.         MonitorInfoBean infoBean = new MonitorInfoBean();  
  75.         infoBean.setFreeMemory(freeMemory);  
  76.         infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);  
  77.         infoBean.setMaxMemory(maxMemory);  
  78.         infoBean.setOsName(osName);  
  79.         infoBean.setTotalMemory(totalMemory);  
  80.         infoBean.setTotalMemorySize(totalMemorySize);  
  81.         infoBean.setTotalThread(totalThread);  
  82.         infoBean.setUsedMemory(usedMemory);  
  83.         infoBean.setCpuRatio(cpuRatio);  
  84.         return infoBean;  
  85.     }  
  86.   
  87.     private static double getCpuRateForLinux() {  
  88.         InputStream is = null;  
  89.         InputStreamReader isr = null;  
  90.         BufferedReader brStat = null;  
  91.         StringTokenizer tokenStat = null;  
  92.         try {  
  93.             System.out.println("Get usage rate of CUP , linux version: "  
  94.                     + linuxVersion);  
  95.   
  96.             Process process = Runtime.getRuntime().exec("top -b -n 1");  
  97.             is = process.getInputStream();  
  98.             isr = new InputStreamReader(is);  
  99.             brStat = new BufferedReader(isr);  
  100.   
  101.             if (linuxVersion.equals("2.4")) {  
  102.                 brStat.readLine();  
  103.                 brStat.readLine();  
  104.                 brStat.readLine();  
  105.                 brStat.readLine();  
  106.   
  107.                 tokenStat = new StringTokenizer(brStat.readLine());  
  108.                 tokenStat.nextToken();  
  109.                 tokenStat.nextToken();  
  110.                 String user = tokenStat.nextToken();  
  111.                 tokenStat.nextToken();  
  112.                 String system = tokenStat.nextToken();  
  113.                 tokenStat.nextToken();  
  114.                 String nice = tokenStat.nextToken();  
  115.   
  116.                 System.out.println(user + " , " + system + " , " + nice);  
  117.   
  118.                 user = user.substring(0, user.indexOf("%"));  
  119.                 system = system.substring(0, system.indexOf("%"));  
  120.                 nice = nice.substring(0, nice.indexOf("%"));  
  121.   
  122.                 float userUsage = new Float(user).floatValue();  
  123.                 float systemUsage = new Float(system).floatValue();  
  124.                 float niceUsage = new Float(nice).floatValue();  
  125.   
  126.                 return (userUsage + systemUsage + niceUsage) / 100;  
  127.             } else {  
  128.                 brStat.readLine();  
  129.                 brStat.readLine();  
  130.   
  131.                 tokenStat = new StringTokenizer(brStat.readLine());  
  132.                 tokenStat.nextToken();  
  133.                 tokenStat.nextToken();  
  134.                 tokenStat.nextToken();  
  135.                 tokenStat.nextToken();  
  136.                 tokenStat.nextToken();  
  137.                 tokenStat.nextToken();  
  138.                 tokenStat.nextToken();  
  139.                 String cpuUsage = tokenStat.nextToken();  
  140.   
  141.                 System.out.println("CPU idle : " + cpuUsage);  
  142.                 Float usage = new Float(cpuUsage.substring(0, cpuUsage  
  143.                         .indexOf("%")));  
  144.   
  145.                 return (1 - usage.floatValue() / 100);  
  146.             }  
  147.   
  148.         } catch (IOException ioe) {  
  149.             System.out.println(ioe.getMessage());  
  150.             freeResource(is, isr, brStat);  
  151.             return 1;  
  152.         } finally {  
  153.             freeResource(is, isr, brStat);  
  154.         }  
  155.   
  156.     }  
  157.   
  158.     private static void freeResource(InputStream is, InputStreamReader isr,  
  159.             BufferedReader br) {  
  160.         try {  
  161.             if (is != null)  
  162.                 is.close();  
  163.             if (isr != null)  
  164.                 isr.close();  
  165.             if (br != null)  
  166.                 br.close();  
  167.         } catch (IOException ioe) {  
  168.             System.out.println(ioe.getMessage());  
  169.         }  
  170.     }  
  171.   
  172.     /** 
  173.      * 获得CPU使用率. 
  174.      *  
  175.      * @return 返回cpu使用率 
  176.      * @author yans 
  177.      */  
  178.     private double getCpuRatioForWindows() {  
  179.         try {  
  180.             String procCmd = System.getenv("windir")  
  181.                     + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"  
  182.                     + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
  183.             // 取进程信息  
  184.             long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));  
  185.             Thread.sleep(CPUTIME);  
  186.             long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));  
  187.             if (c0 != null && c1 != null) {  
  188.                 long idletime = c1[0] - c0[0];  
  189.                 long busytime = c1[1] - c0[1];  
  190.                 return Double.valueOf(  
  191.                         PERCENT * (busytime) / (busytime + idletime))  
  192.                         .doubleValue();  
  193.             } else {  
  194.                 return 0.0;  
  195.             }  
  196.         } catch (Exception ex) {  
  197.             ex.printStackTrace();  
  198.             return 0.0;  
  199.         }  
  200.     }  
  201.   
  202.     /** 
  203.      *  
  204.      * 读取CPU信息. 
  205.      *  
  206.      * @param proc 
  207.      * @return 
  208.      * @author yans 
  209.      */  
  210.     private long[] readCpu(final Process proc) {  
  211.         long[] retn = new long[2];  
  212.         try {  
  213.             proc.getOutputStream().close();  
  214.             InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
  215.             LineNumberReader input = new LineNumberReader(ir);  
  216.             String line = input.readLine();  
  217.             if (line == null || line.length() < FAULTLENGTH) {  
  218.                 return null;  
  219.             }  
  220.             int capidx = line.indexOf("Caption");  
  221.             int cmdidx = line.indexOf("CommandLine");  
  222.             int rocidx = line.indexOf("ReadOperationCount");  
  223.             int umtidx = line.indexOf("UserModeTime");  
  224.             int kmtidx = line.indexOf("KernelModeTime");  
  225.             int wocidx = line.indexOf("WriteOperationCount");  
  226.             long idletime = 0;  
  227.             long kneltime = 0;  
  228.             long usertime = 0;  
  229.             while ((line = input.readLine()) != null) {  
  230.                 if (line.length() < wocidx) {  
  231.                     continue;  
  232.                 }  
  233.                 // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,  
  234.                 // ThreadCount,UserModeTime,WriteOperation  
  235.                 String caption = Bytes.substring(line, capidx, cmdidx - 1)  
  236.                         .trim();  
  237.                 String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();  
  238.                 if (cmd.indexOf("wmic.exe") >= 0) {  
  239.                     continue;  
  240.                 }  
  241.                 // log.info("line="+line);  
  242.                 if (caption.equals("System Idle Process")  
  243.                         || caption.equals("System")) {  
  244.                     idletime += Long.valueOf(  
  245.                             Bytes.substring(line, kmtidx, rocidx - 1).trim())  
  246.                             .longValue();  
  247.                     idletime += Long.valueOf(  
  248.                             Bytes.substring(line, umtidx, wocidx - 1).trim())  
  249.                             .longValue();  
  250.                     continue;  
  251.                 }  
  252.   
  253.                 kneltime += Long.valueOf(  
  254.                         Bytes.substring(line, kmtidx, rocidx - 1).trim())  
  255.                         .longValue();  
  256.                 usertime += Long.valueOf(  
  257.                         Bytes.substring(line, umtidx, wocidx - 1).trim())  
  258.                         .longValue();  
  259.             }  
  260.             retn[0] = idletime;  
  261.             retn[1] = kneltime + usertime;  
  262.             return retn;  
  263.         } catch (Exception ex) {  
  264.             ex.printStackTrace();  
  265.         } finally {  
  266.             try {  
  267.                 proc.getInputStream().close();  
  268.             } catch (Exception e) {  
  269.                 e.printStackTrace();  
  270.             }  
  271.         }  
  272.         return null;  
  273.     }  
  274.   
  275.     /** 
  276.      * 测试方法. 
  277.      *  
  278.      * @param args 
  279.      * @throws Exception 
  280.      * @author yans 
  281.      */  
  282.     public static void main(String[] args) throws Exception {  
  283.         IMonitorService service = new MonitorServiceImpl();  
  284.         MonitorInfoBean monitorInfo = service.getMonitorInfoBean();  
  285.         System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());  
  286.   
  287.         System.out.println("可使用内存=" + monitorInfo.getTotalMemory());  
  288.         System.out.println("剩余内存=" + monitorInfo.getFreeMemory());  
  289.         System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());  
  290.   
  291.         System.out.println("操作系统=" + monitorInfo.getOsName());  
  292.         System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");  
  293.         System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");  
  294.         System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");  
  295.         System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");  
  296.     }  
  297. }  

 

其中,Bytes类用来处理字符串

Java代码  收藏代码
  1. /** 
  2.  * @author yans 
  3.  * @date 2011-10-6 下午11:26:01 
  4.  * @description 
  5.  */  
  6. public class Bytes {  
  7.     public static String substring(String src, int start_idx, int end_idx) {  
  8.         byte[] b = src.getBytes();  
  9.         String tgt = "";  
  10.         for (int i = start_idx; i <= end_idx; i++) {  
  11.             tgt += (char) b[i];  
  12.         }  
  13.         return tgt;  
  14.     }  
  15. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics