java get CPU utilization, system memory, virtual machine memory and so on (without JNI)

2010-05-14  来源:本站原创  分类:Java  人气:233 

Recently had an item is to get the system cpu share information, etc., first thought to use the dynamic link library, but later found to be like this do not call jni, this eliminates the need for many to see the new technology time o ( ∩ _ ∩ ) o. ..

In Java, the total available physical memory, the remaining physical memory, physical memory has been used and other information, the following examples, we can obtain such information, and access to the memory usage under Windows.
Write a MonitorInfoBean first class, some information is used to load monitoring, including physical memory, the remaining physical memory, used physical memory, the memory usage and other fields, such code is as follows:

package com.amgkaka.performance;   

/** *//**   *  Monitoring information JavaBean class  .   * @author  amg   * @version 1.0    * Creation date: 2008-4-25 -  Morning  10:37:00   */  public class MonitorInfoBean {       /** *//**  You can use the memory  . */      private long totalMemory;   

/** *//**  The remaining memory  . */      private long freeMemory;   

/** *//**  The maximum available memory  . */      private long maxMemory;   

/** *//**  The operating system  . */      private String osName;   

/** *//**  Total physical memory  . */      private long totalMemorySize;   

/** *//**  The remaining physical memory  . */      private long freePhysicalMemorySize;   

/** *//**  The physical memory is already in use  . */      private long usedMemory;   

/** *//**  The total number of threads  . */      private int totalThread;   

/** *//** cpu Usage  . */      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;       }   }

Then prepare to receive the current control information interface, the class code is as follows:

package com.amgkaka.performance;   

/** *//**   *  Gets the system information for the business logic class interface  .   * @author amg * @version 1.0    * Creation date: 2008-3-11 -  Morning  10:06:06   */  public interface IMonitorService {       /** *//**       *  Get current monitoring object  .       * @return  Returns the constructed object         * @throws Exception       * @author amgkaka       * Creation date: 2008-4-25 -  Morning  10:45:08       */      public MonitorInfoBean getMonitorInfoBean() throws Exception;   

}

Class of the implementation class MonitorServiceImpl as follows:

package com.amgkaka.performance;   

import java.io.InputStreamReader;   import java.io.LineNumberReader;   

import sun.management.ManagementFactory;   

import com.sun.management.OperatingSystemMXBean;   

/** *//**   *  Get system information business logic implementation class  .   * @author amg * @version 1.0 Creation date: 2008-3-11 -  Morning  10:06:06   */  public class MonitorServiceImpl implements IMonitorService {       // You can set longer, prevent reading to run this system checks when  cpu Occupancy rate, it is not allowed         private static final int CPUTIME = 5000;   

private static final int PERCENT = 100;   

private static final int FAULTLENGTH = 10;   

/** *//**       *  Get current monitoring object  .       * @return  Returns the constructed object         * @throws Exception       * @author amg     * Creation date: 2008-4-25 -  Morning  10:45:08       */      public MonitorInfoBean getMonitorInfoBean() throws Exception {           int kb = 1024;   

//  You can use the memory             long totalMemory = Runtime.getRuntime().totalMemory() / kb;           //  The remaining memory             long freeMemory = Runtime.getRuntime().freeMemory() / kb;           //  The maximum available memory             long maxMemory = Runtime.getRuntime().maxMemory() / kb;   

OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory                   .getOperatingSystemMXBean();   

//  The operating system             String osName = System.getProperty("os.name");           //  Total physical memory             long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;           //  The remaining physical memory             long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;           //  The physical memory is already in use             long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb                   .getFreePhysicalMemorySize())                   / kb;   

//  Get the total number of threads             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();           }   

//  Returns the object constructed             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;       }   

/** *//**       *  Get CPU usage  .       * @return  Returns the CPU usage         * @author amg     * Creation date: 2008-4-25 -  Afternoon  06:05:11       */      private double getCpuRatioForWindows() {           try {               String procCmd = System.getenv("windir")                       + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"                      + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";               //  Get process information                 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;           }       }   

/** *//**       *  Read the CPU information  .       * @param proc       * @return       * @author amg     * Creation date: 2008-4-25 -  Afternoon  06:10:14       */      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;                   }                   //  Field order  :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;       }   

/** *//**       *  The test method  .       * @param args       * @throws Exception       * @author amg     * Creation date: 2008-4-30 -  Afternoon  04:47:29       */      public static void main(String[] args) throws Exception {           IMonitorService service = new MonitorServiceImpl();           MonitorInfoBean monitorInfo = service.getMonitorInfoBean();           System.out.println("cpu Share  =" + monitorInfo.getCpuRatio());   

System.out.println(" You can use the memory  =" + monitorInfo.getTotalMemory());           System.out.println(" The remaining memory  =" + monitorInfo.getFreeMemory());           System.out.println(" The maximum available memory  =" + monitorInfo.getMaxMemory());   

System.out.println(" The operating system  =" + monitorInfo.getOsName());           System.out.println(" Total physical memory  =" + monitorInfo.getTotalMemorySize() + "kb");           System.out.println(" The remaining physical memory  =" + monitorInfo.getFreeMemory() + "kb");           System.out.println(" The physical memory is already in use  =" + monitorInfo.getUsedMemory() + "kb");           System.out.println(" The total number of threads  =" + monitorInfo.getTotalThread() + "kb");       }   }

The implementation class in the need to use a tool to write your own byte class that the code is as follows:

package com.amgkaka.performance;   

/** *//**   * byte Action class  .   * @author amg * @version 1.0    * Creation date: 2008-4-30 -  Afternoon  04:57:23   */  public class Bytes {       /** *//**       *  Because the String.subString on processing problems  ( A Chinese character as a bytes  ), So in         *  A string containing the characters troubles, when you are in the following way  :       * @param src  To crop a string         * @param start_idx  Start the coordinates  ( Include the coordinates  )       * @param end_idx    As of coordinates  ( Include the coordinates  )       * @return       */      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;       }   }

Run under the MonitorBeanImpl class, readers will see the current memory, cpu utilization and other information.

相关文章
  • java get CPU utilization, system memory, virtual machine memory and so on (without JNI) 2010-05-14

    Recently had an item is to get the system cpu share information, etc., first thought to use the dynamic link library, but later found to be like this do not call jni, this eliminates the need for many to see the new technology time o ( ∩ _ ∩ ) o. ..

  • java virtual machine memory to adjust 2010-12-07

    To do with the tomcat server will always be such a problem is not enough memory, the default virtual machine memory is 64M, is clearly not enough. In windows, you can add the value of the environment variable JAVA_OPTS-Xms512m-Xmx1024m to specify the

  • How to configure Tomcat's JVM virtual machine memory size 2010-08-24

    Tomcat itself does not directly run on computers need to rely on hardware-based operating system and a java virtual machine. You can choose your own need to select different operating systems and the corresponding JDK version (as long as is consisten

  • java virtual machine memory settings and tuning 2011-08-15

    The default size of the java virtual machine is relatively small, in the processing of large data will be error java: java.lang.OutOfMemoryError. Set jvm memory means, for a single. Class, you can use the following method Test run the jvm memory sett

  • JAVA virtual machine memory allocation and recovery mechanisms (transfer) 2010-03-29

    Java to the memory divided into two kinds: One is the stack memory, heap memory, one is. In the function defined in some of the basic types of variables and object references to variables in the function of the stack memory allocation. When a block o

  • android virtual machine memory 2010-03-29

    android2.1 the sdk downloaded, the previous memory errors have cropped up all along the pipeline Only reduce the sdk version. Today, in the end all of a sudden whim to ascertain the reason. The specific error: emulator: ERROR: system image file too l

  • Sun Java HotSpot ™ Virtual Machine and garbage collection memory model 2010-06-12

    Previously the company's J2EE application as a result of visits increased by frequent crashes, traced and found the reason for memory and GC, and then some of the information online will be a handful of GC tuning, in fact, that is, tune the tone of s

  • Understanding java JVM virtual machine option Xms Xmx PermSize MaxPermSize difference 2011-07-13

    Eclipse crashes, error messages: MyEclipse has detected that less than 5% of the 64MB of Perm Gen (Non-heap memory) space remains. It is strongly recommended that you exit and restart MyEclipse with new virtual machine memory paramters to increase th

  • Java Virtual Machine class load: Principles. Implementation and Application 2010-07-13

    By jorren on 2005-12-21 15:13:00 I. Introduction Java Virtual Machine (JVM) class loading means will be included in the class file byte code loaded into the JVM, the JVM and make it part of the process. JVM's class of dynamic loading technology can d

  • How to set Tomcat's JVM memory size of virtual machine 2010-10-28

    Tomcat itself does not directly run on a computer, you need to depend on the hardware basis * for the system and a java virtual machine. You can choose your own need to select a different * for the system and the corresponding JDK version (as long as

  • java virtual machine class loading principle. realized. and the application 2010-10-29

    I. Introduction Java Virtual Machine (JVM) class loading means - will be included in the class file byte code loaded into the JVM, and JVM to become part of the process. JVM dynamic class loading techniques can be loaded dynamically at run time or re

  • Java virtual machine class loader: Principles. Implementation and Application 2010-12-01

    Java virtual machine class loader: Principles, Implementation and Application I. Introduction Java Virtual Machine (JVM) class loading means will be included in the byte code class file loaded into the JVM, and JVM to become part of the process. JVM

  • java virtual machine interpreter, compiler-time compilers (rpm) 2011-09-01

    What is java virtual machine: Java Virtual Machine is an imaginary machine, the actual computer simulation software to achieve. Java virtual machine has its own imaginary hardware, such as processor, stack, registers, etc., also has a corresponding i

  • JAVA virtual machine works (turn) 2011-09-01

    JAVA virtual machine works 2009-04-11 21:41:25 | Category: JAVA programming accumulation | Tags: | font size medium and small subscription Java Virtual Machine in between machines and compiler, on any platform are provided to the compiler a common in

  • In-depth Java Virtual Machine for 5 2009-11-28

    Chapter V: JAVA Virtual Machine 1, Java virtual machine is what the 1. Abstract specification; 2. A concrete implementation; 3. A running virtual machine instances (one of three) 2, Java virtual machine life-cycle 1. Each run-time Java virtual machin

  • Java memory management (1. Memory allocation) 2010-03-29

    On the Java memory allocation, and many problems are vague and can not run through a comprehensive understanding. This access to information, desires dig thoroughly clarify java memory allocation context, simply because the level is limited, did not

  • Dalvik virtual machine 2010-03-29

    Google officially released at the end of 2007, a Android SDK, as the Android system, important features, Dalvik virtual machine for the first time into the people's vision. Its efficient use of memory, and in low-speed, high-performance CPU on the sh

  • Virtual machine description (c) 2010-10-18

    Fourth, the virtual machine products From the seventies of last century began to virtual technology in recent years been more and more enterprises and media attention, the virtual computer technology gained considerable development, these are virtual

  • Open Iphone first step (VM7.0 virtual machine to install Snow Leopard Mac OS snow leopard 10.6!) 2010-06-21

    Tools required: VMware workstation 7.0.0 203739 Download Download Address: http://www.vmware.com/cn/products/ws/ VMware workstation 7.0.0 203739 finished package and RI Download: http://download.csdn.net/source/1782243 Virtual Machine sound card disp

  • Virtual machine installation and Oracle10.2.0 RedHatEenterpriseLinux5 install Notes Collection 2010-08-03

    Here is my test environment set up some recording time. Related to how to upload linux in VMware and installed Vmare tools, how to install linux on oracle 10g, how to access linux in windows on the oracle, and operate basic linux commands. Hardware c