java获得CPU使用率,系统内存,虚拟机内存等情况


JXM:Monitoring and Management Interface for the Java™ Platform

通过jmx可以监控vm内存使用,系统内存使用等

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

Java代码   收藏代码
  1.    利用java程序实现获取计算机cpu利用率和内存使用信息。   
  2.   
  3.     创建一个Bean用来存贮要得到的信   
  4.   
  5. public   class  MonitorInfoBean {   
  6.     /** 可使用内存. */    
  7.     private   long  totalMemory;   
  8.      
  9.     /**  剩余内存. */    
  10.     private   long  freeMemory;   
  11.      
  12.     /** 最大可使用内存. */    
  13.     private   long  maxMemory;   
  14.      
  15.     /** 操作系统. */    
  16.     private  String osName;   
  17.      
  18.     /** 总的物理内存. */    
  19.     private   long  totalMemorySize;   
  20.      
  21.     /** 剩余的物理内存. */    
  22.     private   long  freePhysicalMemorySize;   
  23.      
  24.     /** 已使用的物理内存. */    
  25.     private   long  usedMemory;   
  26.      
  27.     /** 线程总数. */    
  28.     private   int  totalThread;   
  29.      
  30.     /** cpu使用率. */    
  31.     private   double  cpuRatio;   
  32.   
  33.     public   long  getFreeMemory() {   
  34.         return  freeMemory;   
  35.     }   
  36.   
  37.     public   void  setFreeMemory( long  freeMemory) {   
  38.         this .freeMemory = freeMemory;   
  39.     }   
  40.   
  41.     public   long  getFreePhysicalMemorySize() {   
  42.         return  freePhysicalMemorySize;   
  43.     }   
  44.   
  45.     public   void  setFreePhysicalMemorySize( long  freePhysicalMemorySize) {   
  46.         this .freePhysicalMemorySize = freePhysicalMemorySize;   
  47.     }   
  48.   
  49.     public   long  getMaxMemory() {   
  50.         return  maxMemory;   
  51.     }   
  52.   
  53.     public   void  setMaxMemory( long  maxMemory) {   
  54.         this .maxMemory = maxMemory;   
  55.     }   
  56.   
  57.     public  String getOsName() {   
  58.         return  osName;   
  59.     }   
  60.   
  61.     public   void  setOsName(String osName) {   
  62.         this .osName = osName;   
  63.     }   
  64.   
  65.     public   long  getTotalMemory() {   
  66.         return  totalMemory;   
  67.     }   
  68.   
  69.     public   void  setTotalMemory( long  totalMemory) {   
  70.         this .totalMemory = totalMemory;   
  71.     }   
  72.   
  73.     public   long  getTotalMemorySize() {   
  74.         return  totalMemorySize;   
  75.     }   
  76.   
  77.     public   void  setTotalMemorySize( long  totalMemorySize) {   
  78.         this .totalMemorySize = totalMemorySize;   
  79.     }   
  80.   
  81.     public   int  getTotalThread() {   
  82.         return  totalThread;   
  83.     }   
  84.   
  85.     public   void  setTotalThread( int  totalThread) {   
  86.         this .totalThread = totalThread;   
  87.     }   
  88.   
  89.     public   long  getUsedMemory() {   
  90.         return  usedMemory;   
  91.     }   
  92.   
  93.     public   void  setUsedMemory( long  usedMemory) {   
  94.         this .usedMemory = usedMemory;   
  95.     }   
  96.   
  97.     public   double  getCpuRatio() {   
  98.         return  cpuRatio;   
  99.     }   
  100.   
  101.     public   void  setCpuRatio( double  cpuRatio) {   
  102.         this .cpuRatio = cpuRatio;   
  103.     }   
  104. }   
  105.   
  106.     之后,建立bean的接口   
  107.   
  108. public   interface  IMonitorService {   
  109.     public  MonitorInfoBean getMonitorInfoBean()  throws  Exception;   
  110.   
  111. }   
  112.   
  113.   然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。   
  114.   
  115. import  java.io.InputStreamReader;   
  116. import  java.io.LineNumberReader;   
  117.   
  118. import  sun.management.ManagementFactory;   
  119.   
  120. import  com.sun.management.OperatingSystemMXBean;   
  121. import  java.io.*;   
  122. import  java.util.StringTokenizer;   
  123.   
  124. /**   
  125.  
  126. * 获取系统信息的业务逻辑实现类.   
  127. * @author GuoHuang   
  128. */    
  129. public   class  MonitorServiceImpl  implements  IMonitorService {   
  130.      
  131.     private   static   final   int  CPUTIME =  30 ;   
  132.   
  133.     private   static   final   int  PERCENT =  100 ;   
  134.   
  135.     private   static   final   int  FAULTLENGTH =  10 ;   
  136.      
  137.     private   static   final  File versionFile =  new  File( "/proc/version" );   
  138.     private   static  String linuxVersion =  null ;   
  139.   
  140.     /**   
  141.      * 获得当前的监控对象.   
  142.      * @return 返回构造好的监控对象   
  143.      * @throws Exception   
  144.      * @author GuoHuang   
  145.      */    
  146.     public  MonitorInfoBean getMonitorInfoBean()  throws  Exception {   
  147.         int  kb =  1024 ;   
  148.          
  149.         // 可使用内存    
  150.         long  totalMemory = Runtime.getRuntime().totalMemory() / kb;   
  151.         // 剩余内存    
  152.         long  freeMemory = Runtime.getRuntime().freeMemory() / kb;   
  153.         // 最大可使用内存    
  154.         long  maxMemory = Runtime.getRuntime().maxMemory() / kb;   
  155.   
  156.         OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory   
  157.                 .getOperatingSystemMXBean();   
  158.   
  159.         // 操作系统    
  160.         String osName = System.getProperty("os.name" );   
  161.         // 总的物理内存    
  162.         long  totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;   
  163.         // 剩余的物理内存    
  164.         long  freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;   
  165.         // 已使用的物理内存    
  166.         long  usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb   
  167.                 .getFreePhysicalMemorySize())   
  168.                 / kb;   
  169.   
  170.         // 获得线程总数    
  171.         ThreadGroup parentThread;   
  172.         for  (parentThread = Thread.currentThread().getThreadGroup(); parentThread   
  173.                 .getParent() != null ; parentThread = parentThread.getParent())   
  174.             ;   
  175.         int  totalThread = parentThread.activeCount();   
  176.   
  177.         double  cpuRatio =  0 ;   
  178.         if  (osName.toLowerCase().startsWith( "windows" )) {   
  179.             cpuRatio = this .getCpuRatioForWindows();   
  180.         }   
  181.         else  {   
  182.          cpuRatio = this .getCpuRateForLinux();   
  183.         }   
  184.          
  185.         // 构造返回对象    
  186.         MonitorInfoBean infoBean = new  MonitorInfoBean();   
  187.         infoBean.setFreeMemory(freeMemory);   
  188.         infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);   
  189.         infoBean.setMaxMemory(maxMemory);   
  190.         infoBean.setOsName(osName);   
  191.         infoBean.setTotalMemory(totalMemory);   
  192.         infoBean.setTotalMemorySize(totalMemorySize);   
  193.         infoBean.setTotalThread(totalThread);   
  194.         infoBean.setUsedMemory(usedMemory);   
  195.         infoBean.setCpuRatio(cpuRatio);   
  196.         return  infoBean;   
  197.     }   
  198.     private   static   double  getCpuRateForLinux(){   
  199.         InputStream is = null ;   
  200.         InputStreamReader isr = null ;   
  201.         BufferedReader brStat = null ;   
  202.         StringTokenizer tokenStat = null ;   
  203.         try {   
  204.             System.out.println("Get usage rate of CUP , linux version: " +linuxVersion);   
  205.   
  206.             Process process = Runtime.getRuntime().exec("top -b -n 1" );   
  207.             is = process.getInputStream();                     
  208.             isr = new  InputStreamReader(is);   
  209.             brStat = new  BufferedReader(isr);   
  210.              
  211.             if (linuxVersion.equals( "2.4" )){   
  212.                 brStat.readLine();   
  213.                 brStat.readLine();   
  214.                 brStat.readLine();   
  215.                 brStat.readLine();   
  216.                  
  217.                 tokenStat = new  StringTokenizer(brStat.readLine());   
  218.                 tokenStat.nextToken();   
  219.                 tokenStat.nextToken();   
  220.                 String user = tokenStat.nextToken();   
  221.                 tokenStat.nextToken();   
  222.                 String system = tokenStat.nextToken();   
  223.                 tokenStat.nextToken();   
  224.                 String nice = tokenStat.nextToken();   
  225.                  
  226.                 System.out.println(user+" , " +system+ " , " +nice);   
  227.                  
  228.                 user = user.substring(0 ,user.indexOf( "%" ));   
  229.                 system = system.substring(0 ,system.indexOf( "%" ));   
  230.                 nice = nice.substring(0 ,nice.indexOf( "%" ));   
  231.                  
  232.                 float  userUsage =  new  Float(user).floatValue();   
  233.                 float  systemUsage =  new  Float(system).floatValue();   
  234.                 float  niceUsage =  new  Float(nice).floatValue();   
  235.                  
  236.                 return  (userUsage+systemUsage+niceUsage)/ 100 ;   
  237.             }else {   
  238.                 brStat.readLine();   
  239.                 brStat.readLine();   
  240.                      
  241.                 tokenStat = new  StringTokenizer(brStat.readLine());   
  242.                 tokenStat.nextToken();   
  243.                 tokenStat.nextToken();   
  244.                 tokenStat.nextToken();   
  245.                 tokenStat.nextToken();   
  246.                 tokenStat.nextToken();   
  247.                 tokenStat.nextToken();   
  248.                 tokenStat.nextToken();   
  249.                 String cpuUsage = tokenStat.nextToken();   
  250.                      
  251.                  
  252.                 System.out.println("CPU idle : " +cpuUsage);   
  253.                 Float usage = new  Float(cpuUsage.substring( 0 ,cpuUsage.indexOf( "%" )));   
  254.                  
  255.                 return  ( 1 -usage.floatValue()/ 100 );   
  256.             }   
  257.   
  258.               
  259.         } catch (IOException ioe){   
  260.             System.out.println(ioe.getMessage());   
  261.             freeResource(is, isr, brStat);   
  262.             return   1 ;   
  263.         } finally {   
  264.             freeResource(is, isr, brStat);   
  265.         }   
  266.   
  267.     }   
  268.     private   static   void  freeResource(InputStream is, InputStreamReader isr, BufferedReader br){   
  269.         try {   
  270.             if (is!= null )   
  271.                 is.close();   
  272.             if (isr!= null )   
  273.                 isr.close();   
  274.             if (br!= null )   
  275.                 br.close();   
  276.         }catch (IOException ioe){   
  277.             System.out.println(ioe.getMessage());   
  278.         }   
  279.     }   
  280.   
  281.   
  282.     /**   
  283.      * 获得CPU使用率.   
  284.      * @return 返回cpu使用率   
  285.      * @author GuoHuang   
  286.      */    
  287.     private   double  getCpuRatioForWindows() {   
  288.         try  {   
  289.             String procCmd = System.getenv("windir" )   
  290.                     + "//system32//wbem//wmic.exe process get Caption,CommandLine,"    
  291.                     + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount" ;   
  292.             // 取进程信息    
  293.             long [] c0 = readCpu(Runtime.getRuntime().exec(procCmd));   
  294.             Thread.sleep(CPUTIME);   
  295.             long [] c1 = readCpu(Runtime.getRuntime().exec(procCmd));   
  296.             if  (c0 !=  null  && c1 !=  null ) {   
  297.                 long  idletime = c1[ 0 ] - c0[ 0 ];   
  298.                 long  busytime = c1[ 1 ] - c0[ 1 ];   
  299.                 return  Double.valueOf(   
  300.                         PERCENT * (busytime) / (busytime + idletime))   
  301.                         .doubleValue();   
  302.             } else  {   
  303.                 return   0.0 ;   
  304.             }   
  305.         } catch  (Exception ex) {   
  306.             ex.printStackTrace();   
  307.             return   0.0 ;   
  308.         }   
  309.     }   
  310.   
  311.     /**        
  312.  
  313. * 读取CPU信息.   
  314.      * @param proc   
  315.      * @return   
  316.      * @author GuoHuang   
  317.      */    
  318.     private   long [] readCpu( final  Process proc) {   
  319.         long [] retn =  new   long [ 2 ];   
  320.         try  {   
  321.             proc.getOutputStream().close();   
  322.             InputStreamReader ir = new  InputStreamReader(proc.getInputStream());   
  323.             LineNumberReader input = new  LineNumberReader(ir);   
  324.             String line = input.readLine();   
  325.             if  (line ==  null  || line.length() < FAULTLENGTH) {   
  326.                 return   null ;   
  327.             }   
  328.             int  capidx = line.indexOf( "Caption" );   
  329.             int  cmdidx = line.indexOf( "CommandLine" );   
  330.             int  rocidx = line.indexOf( "ReadOperationCount" );   
  331.             int  umtidx = line.indexOf( "UserModeTime" );   
  332.             int  kmtidx = line.indexOf( "KernelModeTime" );   
  333.             int  wocidx = line.indexOf( "WriteOperationCount" );   
  334.             long  idletime =  0 ;   
  335.             long  kneltime =  0 ;   
  336.             long  usertime =  0 ;   
  337.             while  ((line = input.readLine()) !=  null ) {   
  338.                 if  (line.length() < wocidx) {   
  339.                     continue ;   
  340.                 }   
  341.                 // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,    
  342.                 // ThreadCount,UserModeTime,WriteOperation    
  343.                 String caption = Bytes.substring(line, capidx, cmdidx - 1 )   
  344.                         .trim();   
  345.                 String cmd = Bytes.substring(line, cmdidx, kmtidx - 1 ).trim();   
  346.                 if  (cmd.indexOf( "wmic.exe" ) >=  0 ) {   
  347.                     continue ;   
  348.                 }   
  349.                 // log.info("line="+line);    
  350.                 if  (caption.equals( "System Idle Process" )   
  351.                         || caption.equals("System" )) {   
  352.                     idletime += Long.valueOf(   
  353.                             Bytes.substring(line, kmtidx, rocidx - 1 ).trim())   
  354.                             .longValue();   
  355.                     idletime += Long.valueOf(   
  356.                             Bytes.substring(line, umtidx, wocidx - 1 ).trim())   
  357.                             .longValue();   
  358.                     continue ;   
  359.                 }   
  360.   
  361.                 kneltime += Long.valueOf(   
  362.                         Bytes.substring(line, kmtidx, rocidx - 1 ).trim())   
  363.                         .longValue();   
  364.                 usertime += Long.valueOf(   
  365.                         Bytes.substring(line, umtidx, wocidx - 1 ).trim())   
  366.                         .longValue();   
  367.             }   
  368.             retn[0 ] = idletime;   
  369.             retn[1 ] = kneltime + usertime;   
  370.             return  retn;   
  371.         } catch  (Exception ex) {   
  372.             ex.printStackTrace();   
  373.         } finally  {   
  374.             try  {   
  375.                 proc.getInputStream().close();   
  376.             } catch  (Exception e) {   
  377.                 e.printStackTrace();   
  378.             }   
  379.         }   
  380.         return   null ;   
  381.     }   
  382.      
  383.     /**     测试方法.   
  384.      * @param args   
  385.      * @throws Exception   
  386.      * @author GuoHuang   
  387.        */    
  388.     public   static   void  main(String[] args)  throws  Exception {   
  389.         IMonitorService service = new  MonitorServiceImpl();   
  390.         MonitorInfoBean monitorInfo = service.getMonitorInfoBean();   
  391.         System.out.println("cpu占有率="  + monitorInfo.getCpuRatio());   
  392.          
  393.         System.out.println("可使用内存="  + monitorInfo.getTotalMemory());   
  394.         System.out.println("剩余内存="  + monitorInfo.getFreeMemory());   
  395.         System.out.println("最大可使用内存="  + monitorInfo.getMaxMemory());   
  396.          
  397.         System.out.println("操作系统="  + monitorInfo.getOsName());   
  398.         System.out.println("总的物理内存="  + monitorInfo.getTotalMemorySize() +  "kb" );   
  399.         System.out.println("剩余的物理内存="  + monitorInfo.getFreeMemory() +  "kb" );   
  400.         System.out.println("已使用的物理内存="  + monitorInfo.getUsedMemory() +  "kb" );   
  401.         System.out.println("线程总数="  + monitorInfo.getTotalThread() +  "kb" );   
  402.     }   
  403. }   
  404.   
  405.     其中,Bytes类用来处理字符串   
  406.   
  407.    public   class  Bytes {   
  408.     public   static  String substring(String src,  int  start_idx,  int  end_idx){   
  409.         byte [] b = src.getBytes();   
  410.         String tgt = "" ;   
  411.         for ( int  i=start_idx; i<=end_idx; i++){   
  412.             tgt +=(char )b[i];   
  413.         }   
  414.         return  tgt;   
  415.     }   
  416. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值