Java obtains CPU usage, system memory, and virtual machine memory (without JNI)

Source: Internet
Author: User

Recently, a project was designed to obtain information about the cpu usage and so on. At first, I thought it was necessary to use a dynamic link library, but later I found that I could do the following without calling jni, this saves a lot of time for reading new technologies...

In Java, you can obtain information such as the total physical memory, the remaining physical memory, and the used physical memory. In the following example, you can obtain the information and the memory usage in Windows.
First, write a MonitorInfoBean class to load monitoring information, including physical memory, remaining physical memory, used physical memory, memory usage, and other fields. The code for this class is as follows:

Package com. hmw. system. monitor; public class MonitorInfoBean {/** memory available. */private long totalMemory;/** remaining memory. */private long freeMemory;/** maximum memory available. */private long maxMemory;/** operating system. */private String osName;/** total physical memory. */private long totalMemorySize;/** remaining physical memory. */private long freePhysicalMemorySize;/** used physical memory. */private long usedMemory;/** 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 ;}}

 

Next, write an interface to obtain the current monitoring information. The code for this class is as follows:

Package com. hmw. system. monitor;/*** business logic interface for retrieving system information. */public interface IMonitorService {/*** get the current Monitored object. * @ return returns the constructed Monitored object * @ throws Exception */public MonitorInfoBean getMonitorInfoBean () throws Exception ;}

 

The implementation class MonitorServiceImpl of this class is as follows:

Package COM. HMW. system. monitor; import Java. io. bufferedreader; 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;/***** business logic implementation class for retrieving system information. ** @ author guohuang */public class monitorserviceimpl implements imonitorse Rvice {Private Static final int cputime = 30; Private Static final int percent = 100; Private Static final int faultlength = 10; Private Static string linuxversion = NULL; /*** get the current Monitored object. ** @ return returns the constructed Monitored object * @ throws exception * @ author guohuang */Public monitorinfobean getmonitorinfobean () throws exception {int kb = 1024; // memory can be used long totalmemory = runtime. getruntime (). totalmemory ()/kb; // remaining memory l Ong freememory = runtime. getruntime (). freememory ()/kb; // maximum memory available long maxmemory = runtime. getruntime (). maxmemory ()/kb; operatingsystemmxbean osmxb = (operatingsystemmxbean) managementfactory. getoperatingsystemmxbean (); // operating system string osname = system. getproperty ("OS. name "); // total physical memory long totalmemorysize = osmxb. gettotalphysicalmemorysize ()/kb; // The remaining physical memory is long freephysicalmemorysize = osmxb. getfreeph Ysicalmemorysize ()/kb; // used physical memory long usedmemory = (osmxb. gettotalphysicalmemorysize ()-osmxb. getfreephysicalmemorysize ()/kb; // obtain 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 ();} else {cpuratio = getcpurateforlinux ();} // construct the returned object monitorinfobean infobean = new monitorinfobean (); infobean. setfreememory (freememory); infobean. setfreephysicalmemorysize (freephysicalmemorysize); infob EAN. 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 Tok ENSTAT = NULL; try {system. out. println ("Get usage rate of cup, Linux version:" + linuxversion); Process = runtime.getruntime(cmd.exe C ("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. readli Ne (); 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 ("%"); f Loat 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 v Oid 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 () ;}}/*** get CPU usage. ** @ return returns CPU usage * @ author guohuang */private double getcpuratioforwindows () {try {string proccmd = system. getenv ("WINDIR") + "// system32 // WBEM // wmic.exe process get caption, CommandLine, kernelmodetime, readoperationcount, threadcount, usermodetime, writeoperationcount "; // obtain the process information long [] C0 = readcpu (run Time.getruntime(cmd.exe C (proccmd); thread. Sleep (cputime); long [] C1 = readcpu(runtime.getruntime(cmd.exe C (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 CPU information. * @ Param proc * @ return * @ author guohuang */private long [] readcpu (final process proc) {long [] retn = new long [2]; try {Proc. getoutputstream (). close (); inputs Treamreader 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;} // the order in which the fields appear: caption, CommandLine, kernelmodetime, readoperationcount, // threadcount, usermodetime, writeoperationstring caption = bytes. substring (line, capidx, cmdidx-1 ). trim (); string cmd = bytes. substring (line, cmdidx, kmtidx-1 ). trim (); If (CMD. indexof ("wmic.exe")> = 0) {continue;} string S1 = bytes. substring (line, kmtidx, rocidx-1 ). trim (); string S2 = bytes. substring (line, umtidx, wocidx-1 ). trim (); If (caption. equals ("system idle Process") | caption. equals ("system") {If (s1.length ()> 0) idletime + = long. valueof (S1 ). longvalue (); If (s2.length ()> 0) idletime + = long. valueof (S2 ). longvalue (); continue;} If (s1.length ()> 0) kneltime + = long. valueof (S1 ). longvalue (); If (s2.length ()> 0) usertime + = long. valueof (S2 ). 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;}/*** test method. ** @ Param ARGs * @ throws exception * @ author guohuang */public static void main (string [] ARGs) throws exception {imonitorservice service = new monitorserviceimpl (); monitorinfobean monitorinfo = service. getmonitorinfobean (); system. out. println ("CPU usage =" + monitorinfo. getcpuratio (); system. out. println ("memory available =" + monitorinfo. gettotalmemory (); system. out. println ("remaining memory =" + monitorinfo. getfreememory (); system. out. println ("maximum available memory =" + monitorinfo. getmaxmemory (); system. out. println ("Operating System =" + monitorinfo. getOSName (); system. out. println ("total physical memory =" + monitorinfo. gettotalmemorysize () + "kb"); system. out. println ("remaining physical memory =" + monitorinfo. getfreememory () + "kb"); system. out. println ("used physical memory =" + monitorinfo. getusedmemory () + "kb"); system. out. println ("Total number of threads =" + monitorinfo. gettotalthread () + "kb ");}}

 

This implementation class requires a tool class for writing byte by yourself. The code for this class is as follows:

Package com. hmw. system. monitor;/*** byte operation class. */public class Bytes {/*** due to String. subString has a problem in Chinese Character Processing (one Chinese character is considered as one byte). Therefore, there is a hidden danger in character strings containing Chinese characters. The following adjustments are made: ** @ param src: the string to be intercepted * @ param start_idx start coordinate (including the coordinate) * @ param end_idx end coordinate (including the coordinate) * @ 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 ;}}

When you run the MonitorBeanImpl class, the reader will see the current memory, cpu utilization, and other information.

 

 

Source: http://kakaluyi.javaeye.com/blog/211492

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.