java获取计算机cpu利用率和内存使用信息

标签: java 计算机 cpu | 发表时间:2015-09-23 07:30 | 作者:xiaoyu123456
出处:http://www.iteye.com
利用java获取计算机cpu利用率和内存使用信息
1.pojo类:
public class MonitorInfoBean {
    /** 可使用内存. */
    private long totalMemory;
   
    /** 剩余内存. */
    private long freeMemory;
   
    /** 最大可使用内存. */
    private long maxMemory;
   
    /** 操作系统. */
    private String osName;
   
    /** 总的物理内存. */
    private long totalMemorySize;
   
    /** 剩余的物理内存. */
    private long freePhysicalMemorySize;
   
    /** 已使用的物理内存. */
    private long usedMemory;
   
    /** 线程总数. */
    private int totalThread;
   
    /** cpu使用率. */
    private double cpuRatio;
    public long getFreeMemory() {
        return freeMemory;
    }
    public void setFreeMemory(long freeMemory) {
        this.freeMemory = freeMemory;
    }
    public long getFreePhysicalMemorySize() {
        return freePhysicalMemorySize;
    }
    public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
        this.freePhysicalMemorySize = freePhysicalMemorySize;
    }
    public long getMaxMemory() {
        return maxMemory;
    }
    public void setMaxMemory(long maxMemory) {
        this.maxMemory = maxMemory;
    }
    public String getOsName() {
        return osName;
    }
    public void setOsName(String osName) {
        this.osName = osName;
    }
    public long getTotalMemory() {
        return totalMemory;
    }
    public void setTotalMemory(long totalMemory) {
        this.totalMemory = totalMemory;
    }
    public long getTotalMemorySize() {
        return totalMemorySize;
    }
    public void setTotalMemorySize(long totalMemorySize) {
        this.totalMemorySize = totalMemorySize;
    }
    public int getTotalThread() {
        return totalThread;
    }
    public void setTotalThread(int totalThread) {
        this.totalThread = totalThread;
    }
    public long getUsedMemory() {
        return usedMemory;
    }
    public void setUsedMemory(long usedMemory) {
        this.usedMemory = usedMemory;
    }
    public double getCpuRatio() {
        return cpuRatio;
    }
    public void setCpuRatio(double cpuRatio) {
        this.cpuRatio = cpuRatio;
    }
}
2. 实现类:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.StringTokenizer;
import sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

public class cpu {
    private static final int CPUTIME = 30;
      private static final int PERCENT = 100;
      private static final int FAULTLENGTH = 10;
     
      private static final File versionFile = new File("/proc/version");
      private static String linuxVersion = null;
            public double getCpuRatio(){
            // 操作系统
          String osName = System.getProperty("os.name");
            double cpuRatio = 0;
           if (osName.toLowerCase().startsWith("windows")) {
               return cpuRatio = this.getCpuRatioForWindows();
           }
           else {
               return cpuRatio = this.getCpuRateForLinux();
           }
            }
     
      /**
       * 获得当前的监控对象.
       * @return 返回构造好的监控对象
       */
      public MonitorInfoBean getMonitorInfoBean() throws Exception {
          int kb = 1024;
         
          // 可使用内存
          long totalMemory = Runtime.getRuntime().totalMemory() / kb;
          // 剩余内存
          long freeMemory = Runtime.getRuntime().freeMemory() / kb;
          // 最大可使用内存
          long maxMemory = Runtime.getRuntime().maxMemory() / kb;
          OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
                  .getOperatingSystemMXBean();
          // 操作系统
          String osName = System.getProperty("os.name");
          // 总的物理内存
          long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
          // 剩余的物理内存
          long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
          // 已使用的物理内存
          long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
                  .getFreePhysicalMemorySize())
                  / kb;
          // 获得线程总数
          ThreadGroup parentThread;
          for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
                  .getParent() != null; parentThread = parentThread.getParent())
              ;
          int totalThread = parentThread.activeCount();
          double cpuRatio = 0;
          if (osName.toLowerCase().startsWith("windows")) {
              cpuRatio = this.getCpuRatioForWindows();
          }
          else {
           cpuRatio = this.getCpuRateForLinux();
          }
         
          // 构造返回对象
          MonitorInfoBean infoBean = new MonitorInfoBean();
          infoBean.setFreeMemory(freeMemory);
          infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
          infoBean.setMaxMemory(maxMemory);
          infoBean.setOsName(osName);
          infoBean.setTotalMemory(totalMemory);
          infoBean.setTotalMemorySize(totalMemorySize);
          infoBean.setTotalThread(totalThread);
          infoBean.setUsedMemory(usedMemory);
          infoBean.setCpuRatio(cpuRatio);
          return infoBean;
      }
      private static double getCpuRateForLinux(){
          InputStream is = null;
          InputStreamReader isr = null;
          BufferedReader brStat = null;
          StringTokenizer tokenStat = null;
          try{
              System.out.println("Get usage rate of CUP , linux version: "+linuxVersion);
              Process process = Runtime.getRuntime().exec("top -b -n 1");
              is = process.getInputStream();                   
              isr = new InputStreamReader(is);
              brStat = new BufferedReader(isr);
             
              if(linuxVersion.equals("2.4")){
                  brStat.readLine();
                  brStat.readLine();
                  brStat.readLine();
                  brStat.readLine();
                 
                  tokenStat = new StringTokenizer(brStat.readLine());
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  String user = tokenStat.nextToken();
                  tokenStat.nextToken();
                  String system = tokenStat.nextToken();
                  tokenStat.nextToken();
                  String nice = tokenStat.nextToken();
                 
                  System.out.println(user+" , "+system+" , "+nice);
                 
                  user = user.substring(0,user.indexOf("%"));
                  system = system.substring(0,system.indexOf("%"));
                  nice = nice.substring(0,nice.indexOf("%"));
                 
                  float userUsage = new Float(user).floatValue();
                  float systemUsage = new Float(system).floatValue();
                  float niceUsage = new Float(nice).floatValue();
                 
                  return (userUsage+systemUsage+niceUsage)/100;
              }else{
                  brStat.readLine();
                  brStat.readLine();
                     
                  tokenStat = new StringTokenizer(brStat.readLine());
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  tokenStat.nextToken();
                  String cpuUsage = tokenStat.nextToken();
                     
                 
                  System.out.println("CPU idle : "+cpuUsage);
                  Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));
                 
                  return (1-usage.floatValue()/100);
              }
              
          } catch(IOException ioe){
              System.out.println(ioe.getMessage());
              freeResource(is, isr, brStat);
              return 1;
          } finally{
              freeResource(is, isr, brStat);
          }
      }
      private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
          try{
              if(is!=null)
                  is.close();
              if(isr!=null)
                  isr.close();
              if(br!=null)
                  br.close();
          }catch(IOException ioe){
              System.out.println(ioe.getMessage());
          }
      }

      /**
       * 获得CPU使用率.
       * @return 返回cpu使用率
       */
      private double getCpuRatioForWindows() {
          try {
              String procCmd = System.getenv("windir")
                      + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
                      + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
              // 取进程信息
              long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
              Thread.sleep(CPUTIME);
              long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
              if (c0 != null && c1 != null) {
                  long idletime = c1[0] - c0[0];
                  long busytime = c1[1] - c0[1];
                  return Double.valueOf(
                          PERCENT * (busytime) / (busytime + idletime))
                          .doubleValue();
              } else {
                  return 0.0;
              }
          } catch (Exception ex) {
              ex.printStackTrace();
              return 0.0;
          }
      }
      /**   
   * 读取CPU信息.
       * @param proc
       */
      private long[] readCpu(final Process proc) {
          long[] retn = new long[2];
          try {
              proc.getOutputStream().close();
              InputStreamReader ir = new InputStreamReader(proc.getInputStream());
              LineNumberReader input = new LineNumberReader(ir);
              String line = input.readLine();
              if (line == null || line.length() < FAULTLENGTH) {
                  return null;
              }
              int capidx = line.indexOf("Caption");
              int cmdidx = line.indexOf("CommandLine");
              int rocidx = line.indexOf("ReadOperationCount");
              int umtidx = line.indexOf("UserModeTime");
              int kmtidx = line.indexOf("KernelModeTime");
              int wocidx = line.indexOf("WriteOperationCount");
              long idletime = 0;
              long kneltime = 0;
              long usertime = 0;
              while ((line = input.readLine()) != null) {
                  if (line.length() < wocidx) {
                      continue;
                  }
                  // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
                  // ThreadCount,UserModeTime,WriteOperation
                  String caption = Bytes.substring(line, capidx, cmdidx - 1)
                          .trim();
                  String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
                  if (cmd.indexOf("wmic.exe") >= 0) {
                      continue;
                  }
                  // log.info("line="+line);
                  if (caption.equals("System Idle Process")
                          || caption.equals("System")) {
                      idletime += Long.valueOf(
                              Bytes.substring(line, kmtidx, rocidx - 1).trim())
                              .longValue();
                      idletime += Long.valueOf(
                              Bytes.substring(line, umtidx, wocidx - 1).trim())
                              .longValue();
                      continue;
                  }
                  kneltime += Long.valueOf(
                          Bytes.substring(line, kmtidx, rocidx - 1).trim())
                          .longValue();
                  usertime += Long.valueOf(
                          Bytes.substring(line, umtidx, wocidx - 1).trim())
                          .longValue();
              }
              retn[0] = idletime;
              retn[1] = kneltime + usertime;
              return retn;
          } catch (Exception ex) {
              ex.printStackTrace();
          } finally {
              try {
                  proc.getInputStream().close();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          return null;
      }
     
      /**     测试方法.
       * @param args
       * @throws Exception
         */
      public static void main(String[] args) throws Exception {
      cpu c =new cpu();
      System.out.println("cpu占有率1=" + c.getCpuRatio());
      System.out.println("cpu占有率2=" + c.getCpuRatioForWindows());
          MonitorInfoBean monitorInfo = c.getMonitorInfoBean();
          System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());
         
          System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
          System.out.println("剩余内存=" + monitorInfo.getFreeMemory());
          System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());
         
          System.out.println("操作系统=" + monitorInfo.getOsName());
          System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");
          System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");
          System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");
          System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");
      }

}
class Bytes {
    public static String substring(String src, int start_idx, int end_idx){
        byte[] b = src.getBytes();
        String tgt = "";
        for(int i=start_idx; i<=end_idx; i++){
            tgt +=(char)b[i];
        }
        return tgt;
    }
}


该文章转自:
http://blog.csdn.net/farreaching665/article/details/7098839

已有 0 人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐



相关 [java 计算机 cpu] 推荐:

JAVA获取计算机CPU、硬盘、主板、网络等信息

- - 编程语言 - ITeye博客
l转[ http://www.cnblogs.com/jifeng/archive/2012/05/16/2503519.html]. 通过使用第三方开源jar包sigar.jar我们可以获得本地的信息. 1.下载sigar.jar. 2.按照主页上的说明解压包后将相应的文件copy到java路径.

java获取计算机cpu利用率和内存使用信息

- - Java - 编程语言 - ITeye博客
利用java获取计算机cpu利用率和内存使用信息.     /** 最大可使用内存.     /** 剩余的物理内存.     /** 已使用的物理内存.             // 操作系统.        * 获得当前的监控对象.        * @return 返回构造好的监控对象.           // 可使用内存.

从Java视角理解CPU缓存(CPU Cache)

- - 淘宝网通用产品团队博客
从Java视角理解系统结构连载, 关注我的微博( 链接)了解最新动态众所周知, CPU是计算机的大脑, 它负责执行程序的指令; 内存负责存数据, 包括程序自身数据. 同样大家都知道, 内存比CPU慢很多. 其实在30年前, CPU的频率和内存总线的频率在同一个级别, 访问内存只比访问CPU寄存器慢一点儿.

Java定位CPU使用100%的方法

- cong - 龙浩的blog
流程:把线程dump出来,然后分析. 1:Threaddump的方法:. jvisualvm中来thread dump.  对应的线程id是十进制的,需要转换为十六进制的在threaddump文件中才可以看到. 找到对应的线程,把相关的方法找出来,可以精确到代码的行号,自己修改相关源码来fix bug.

写Java也得了解CPU缓存

- - 忘我的追寻
CPU,一般认为写C/C++的才需要了解,写高级语言的(Java/C#/pathon…)并不需要了解那么底层的东西. 我一开始也是这么想的,但直到碰到LMAX的 Disruptor,以及 马丁的博文,才发现写Java的,更加不能忽视CPU. 经过一段时间的阅读,希望总结一下自己的阅读后的感悟. 本文主要谈谈CPU缓存对Java编程的影响,不涉及具体CPU缓存的机制和实现.

java在CPU中的一些个破事

- - ImportNew
还是那句话,貌似java和CPU没有多少关系,我们现在来聊聊有啥关系;. 这三个步骤来完成,从这点你也能看出i++为什么能实现先做其他的事情再自我加1,因为它讲值赋予给了另一个变量. 2、我们要用到多线程并发一致性,就需要用到锁的机制,目前类似Atomic*的东西基本可以满足这些要求,内部提供了很多unsafe类的方法,通过不断对比绝对可见性的数据来保证获取的数据是最新的;接下来我们继续来说一些CPU其他的事情.

快速定位消耗CPU的Java线程

- - BlogJava_首页
1.通过快递定位消耗CPU的线程.     工具: Window 平台 通过 Processor  explorer 获得线程ID .     Linux 通过 top -H 获得. 然后通过Thread dump 获得java 所有线程 搜索到相应的线程ID 定位该线程.     可以通过 Java 内置的jvisualvm  或者Jstack.

从Java视角理解CPU上下文切换(Context Switch)

- - 淘宝网通用产品团队博客
从Java视角理解系统结构连载, 关注我的微博( 链接)了解最新动态在高性能编程时,经常接触到多线程. 起初我们的理解是, 多个线程并行地执行总比单个线程要快, 就像多个人一起干活总比一个人干要快. 然而实际情况是, 多线程之间需要竞争IO设备, 或者竞争锁资源,导致往往执行速度还不如单个线程. 在这里有一个经常提及的概念就是: 上下文切换(Context Switch).

Linux下java进程CPU占用率高-分析方法

- - Linux - 操作系统 - ITeye博客
今天登陆同事的一台gateway 开始以为hive环境登陆不了了,仔细一看看了下是因为机器很卡,我每次等几秒没登陆就ctrl+c了,看了下是有个java进程cpu:340.4%  mem:14.6%. 一般解决方法是通过top命令找出消耗资源高的线程id,利用strace命令查看该线程所有系统调用.

java问题导致linux负载、cpu过高如何定位

- - CSDN博客推荐文章
1.用top找到最耗资源的进程id. 2.查询最消耗资源的java进程. 3.打印java 栈 信息. 4.将耗资源的javaPID转换为16进制(5920转1720<16进制>  去百度找 :十进制转十六进制). PID 对应 堆栈中的nid(16进制). 去stack.txt 中查找nid=1720的问题.