用Java获得当前性能信息

 在Java中,可以获得总的物理内存、剩余的物理内存、已使用的物理内存等信息,本例讲解如何取得这些信息,并且获得在Windows下的内存使用率。
     首先编写一个MonitorInfoBean类,用来装载监控的一些信息,包括物理内存、剩余的物理内存、已使用的物理内存、内存使用率等字段,该类的代码如下:
  1. package com.amigo.performance;
  2. /** *//**
  3.  * 监视信息的JavaBean类.
  4.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  5.  * @version 1.0 
  6.  * Creation date: 2008-4-25 - 上午10:37:00
  7.  */
  8. public class MonitorInfoBean {
  9.     /** *//** 可使用内存. */
  10.     private long totalMemory;
  11.     
  12.     /** *//** 剩余内存. */
  13.     private long freeMemory;
  14.     
  15.     /** *//** 最大可使用内存. */
  16.     private long maxMemory;
  17.     
  18.     /** *//** 操作系统. */
  19.     private String osName;
  20.     
  21.     /** *//** 总的物理内存. */
  22.     private long totalMemorySize;
  23.     
  24.     /** *//** 剩余的物理内存. */
  25.     private long freePhysicalMemorySize;
  26.     
  27.     /** *//** 已使用的物理内存. */
  28.     private long usedMemory;
  29.     
  30.     /** *//** 线程总数. */
  31.     private int totalThread;
  32.     
  33.     /** *//** cpu使用率. */
  34.     private double cpuRatio;
  35.     public long getFreeMemory() {
  36.         return freeMemory;
  37.     }
  38.     public void setFreeMemory(long freeMemory) {
  39.         this.freeMemory = freeMemory;
  40.     }
  41.     public long getFreePhysicalMemorySize() {
  42.         return freePhysicalMemorySize;
  43.     }
  44.     public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
  45.         this.freePhysicalMemorySize = freePhysicalMemorySize;
  46.     }
  47.     public long getMaxMemory() {
  48.         return maxMemory;
  49.     }
  50.     public void setMaxMemory(long maxMemory) {
  51.         this.maxMemory = maxMemory;
  52.     }
  53.     public String getOsName() {
  54.         return osName;
  55.     }
  56.     public void setOsName(String osName) {
  57.         this.osName = osName;
  58.     }
  59.     public long getTotalMemory() {
  60.         return totalMemory;
  61.     }
  62.     public void setTotalMemory(long totalMemory) {
  63.         this.totalMemory = totalMemory;
  64.     }
  65.     public long getTotalMemorySize() {
  66.         return totalMemorySize;
  67.     }
  68.     public void setTotalMemorySize(long totalMemorySize) {
  69.         this.totalMemorySize = totalMemorySize;
  70.     }
  71.     public int getTotalThread() {
  72.         return totalThread;
  73.     }
  74.     public void setTotalThread(int totalThread) {
  75.         this.totalThread = totalThread;
  76.     }
  77.     public long getUsedMemory() {
  78.         return usedMemory;
  79.     }
  80.     public void setUsedMemory(long usedMemory) {
  81.         this.usedMemory = usedMemory;
  82.     }
  83.     public double getCpuRatio() {
  84.         return cpuRatio;
  85.     }
  86.     public void setCpuRatio(double cpuRatio) {
  87.         this.cpuRatio = cpuRatio;
  88.     }
  89. }

 

 接着编写一个获得当前的监控信息的接口,该类的代码如下所示:

  1. package com.amigo.performance;
  2. /** *//**
  3.  * 获取系统信息的业务逻辑类接口.
  4.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  5.  * @version 1.0 
  6.  * Creation date: 2008-3-11 - 上午10:06:06
  7.  */
  8. public interface IMonitorService {
  9.     /** *//**
  10.      * 获得当前的监控对象.
  11.      * @return 返回构造好的监控对象
  12.      * @throws Exception
  13.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  14.      * Creation date: 2008-4-25 - 上午10:45:08
  15.      */
  16.     public MonitorInfoBean getMonitorInfoBean() throws Exception;
  17. }

 

 该类的实现类MonitorServiceImpl如下所示:

  1. package com.amigo.performance;
  2. import java.io.InputStreamReader;
  3. import java.io.LineNumberReader;
  4. import sun.management.ManagementFactory;
  5. import com.sun.management.OperatingSystemMXBean;
  6. /** *//**
  7.  * 获取系统信息的业务逻辑实现类.
  8.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  9.  * @version 1.0 Creation date: 2008-3-11 - 上午10:06:06
  10.  */
  11. public class MonitorServiceImpl implements IMonitorService {
  12.     
  13.     private static final int CPUTIME = 30;
  14.     private static final int PERCENT = 100;
  15.     private static final int FAULTLENGTH = 10;
  16.     /** *//**
  17.      * 获得当前的监控对象.
  18.      * @return 返回构造好的监控对象
  19.      * @throws Exception
  20.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  21.      * Creation date: 2008-4-25 - 上午10:45:08
  22.      */
  23.     public MonitorInfoBean getMonitorInfoBean() throws Exception {
  24.         int kb = 1024;
  25.         
  26.         // 可使用内存
  27.         long totalMemory = Runtime.getRuntime().totalMemory() / kb;
  28.         // 剩余内存
  29.         long freeMemory = Runtime.getRuntime().freeMemory() / kb;
  30.         // 最大可使用内存
  31.         long maxMemory = Runtime.getRuntime().maxMemory() / kb;
  32.         OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
  33.                 .getOperatingSystemMXBean();
  34.         // 操作系统
  35.         String osName = System.getProperty("os.name");
  36.         // 总的物理内存
  37.         long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
  38.         // 剩余的物理内存
  39.         long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
  40.         // 已使用的物理内存
  41.         long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
  42.                 .getFreePhysicalMemorySize())
  43.                 / kb;
  44.         // 获得线程总数
  45.         ThreadGroup parentThread;
  46.         for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
  47.                 .getParent() != null; parentThread = parentThread.getParent())
  48.             ;
  49.         int totalThread = parentThread.activeCount();
  50.         double cpuRatio = 0;
  51.         if (osName.toLowerCase().startsWith("windows")) {
  52.             cpuRatio = this.getCpuRatioForWindows();
  53.         }
  54.         
  55.         // 构造返回对象
  56.         MonitorInfoBean infoBean = new MonitorInfoBean();
  57.         infoBean.setFreeMemory(freeMemory);
  58.         infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
  59.         infoBean.setMaxMemory(maxMemory);
  60.         infoBean.setOsName(osName);
  61.         infoBean.setTotalMemory(totalMemory);
  62.         infoBean.setTotalMemorySize(totalMemorySize);
  63.         infoBean.setTotalThread(totalThread);
  64.         infoBean.setUsedMemory(usedMemory);
  65.         infoBean.setCpuRatio(cpuRatio);
  66.         return infoBean;
  67.     }
  68.     /** *//**
  69.      * 获得CPU使用率.
  70.      * @return 返回cpu使用率
  71.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  72.      * Creation date: 2008-4-25 - 下午06:05:11
  73.      */
  74.     private double getCpuRatioForWindows() {
  75.         try {
  76.             String procCmd = System.getenv("windir")
  77.                     + "//system32//wbem//wmic.exe process get Caption,CommandLine,"
  78.                     + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
  79.             // 取进程信息
  80.             long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
  81.             Thread.sleep(CPUTIME);
  82.             long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
  83.             if (c0 != null && c1 != null) {
  84.                 long idletime = c1[0] - c0[0];
  85.                 long busytime = c1[1] - c0[1];
  86.                 return Double.valueOf(
  87.                         PERCENT * (busytime) / (busytime + idletime))
  88.                         .doubleValue();
  89.             } else {
  90.                 return 0.0;
  91.             }
  92.         } catch (Exception ex) {
  93.             ex.printStackTrace();
  94.             return 0.0;
  95.         }
  96.     }
  97.     /** *//**
  98.      * 读取CPU信息.
  99.      * @param proc
  100.      * @return
  101.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  102.      * Creation date: 2008-4-25 - 下午06:10:14
  103.      */
  104.     private long[] readCpu(final Process proc) {
  105.         long[] retn = new long[2];
  106.         try {
  107.             proc.getOutputStream().close();
  108.             InputStreamReader ir = new InputStreamReader(proc.getInputStream());
  109.             LineNumberReader input = new LineNumberReader(ir);
  110.             String line = input.readLine();
  111.             if (line == null || line.length() < FAULTLENGTH) {
  112.                 return null;
  113.             }
  114.             int capidx = line.indexOf("Caption");
  115.             int cmdidx = line.indexOf("CommandLine");
  116.             int rocidx = line.indexOf("ReadOperationCount");
  117.             int umtidx = line.indexOf("UserModeTime");
  118.             int kmtidx = line.indexOf("KernelModeTime");
  119.             int wocidx = line.indexOf("WriteOperationCount");
  120.             long idletime = 0;
  121.             long kneltime = 0;
  122.             long usertime = 0;
  123.             while ((line = input.readLine()) != null) {
  124.                 if (line.length() < wocidx) {
  125.                     continue;
  126.                 }
  127.                 // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
  128.                 // ThreadCount,UserModeTime,WriteOperation
  129.                 String caption = Bytes.substring(line, capidx, cmdidx - 1)
  130.                         .trim();
  131.                 String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
  132.                 if (cmd.indexOf("wmic.exe") >= 0) {
  133.                     continue;
  134.                 }
  135.                 // log.info("line="+line);
  136.                 if (caption.equals("System Idle Process")
  137.                         || caption.equals("System")) {
  138.                     idletime += Long.valueOf(
  139.                             Bytes.substring(line, kmtidx, rocidx - 1).trim())
  140.                             .longValue();
  141.                     idletime += Long.valueOf(
  142.                             Bytes.substring(line, umtidx, wocidx - 1).trim())
  143.                             .longValue();
  144.                     continue;
  145.                 }
  146.                 kneltime += Long.valueOf(
  147.                         Bytes.substring(line, kmtidx, rocidx - 1).trim())
  148.                         .longValue();
  149.                 usertime += Long.valueOf(
  150.                         Bytes.substring(line, umtidx, wocidx - 1).trim())
  151.                         .longValue();
  152.             }
  153.             retn[0] = idletime;
  154.             retn[1] = kneltime + usertime;
  155.             return retn;
  156.         } catch (Exception ex) {
  157.             ex.printStackTrace();
  158.         } finally {
  159.             try {
  160.                 proc.getInputStream().close();
  161.             } catch (Exception e) {
  162.                 e.printStackTrace();
  163.             }
  164.         }
  165.         return null;
  166.     }
  167.     
  168.     /** *//**
  169.      * 测试方法.
  170.      * @param args
  171.      * @throws Exception
  172.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  173.      * Creation date: 2008-4-30 - 下午04:47:29
  174.      */
  175.     public static void main(String[] args) throws Exception {
  176.         IMonitorService service = new MonitorServiceImpl();
  177.         MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
  178.         System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());
  179.         
  180.         System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
  181.         System.out.println("剩余内存=" + monitorInfo.getFreeMemory());
  182.         System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());
  183.         
  184.         System.out.println("操作系统=" + monitorInfo.getOsName());
  185.         System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");
  186.         System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");
  187.         System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");
  188.         System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");
  189.     }
  190. }

该实现类中需要用到一个自己编写byte的工具类,该类的代码如下所示:


 

  1. package com.amigo.performance;
  2. /** *//**
  3.  * byte操作类.
  4.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
  5.  * @version 1.0 
  6.  * Creation date: 2008-4-30 - 下午04:57:23
  7.  */
  8. public class Bytes {
  9.     /** *//**
  10.      * 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在
  11.      * 包含汉字的字符串时存在隐患,现调整如下:
  12.      * @param src 要截取的字符串
  13.      * @param start_idx 开始坐标(包括该坐标)
  14.      * @param end_idx   截止坐标(包括该坐标)
  15.      * @return
  16.      */
  17.     public static String substring(String src, int start_idx, int end_idx){
  18.         byte[] b = src.getBytes();
  19.         String tgt = "";
  20.         for(int i=start_idx; i<=end_idx; i++){
  21.             tgt +=(char)b[i];
  22.         }
  23.         return tgt;
  24.     }
  25. }

运行下MonitorServiceImpl类,读者将会看到当前的内存、cpu利用率等信息。

 

原文引自:http://www.blogjava.net/amigoxie/archive/2008/04/30/197564.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值