Obtain real-time cpu and memory information in linux using java

Source: Internet
Author: User

From: http://avery-leo.javaeye.com/blog/298724

Source code:

  1. Import java. io. BufferedReader;
  2. Import java. io. File;
  3. Import java. io. FileInputStream;
  4. Import java. io. IOException;
  5. Import java. io. InputStreamReader;
  6. Import java.net. InetAddress;
  7. Import java. util. StringTokenizer;
  8. Import org. apache. log4j. Logger;
  9. /**
  10. * Obtain cpu and memory information in linux
  11. *
  12. * <P>
  13. *
  14. * @ Author leo
  15. * </P>
  16. * @ Date 2008
  17. */
  18. Public final class linuxsystemtool implements runnable {
  19. Private logger log = logger. getlogger (linuxsystemtool. Class );
  20. Private config Config = config. getinstance ();
  21. /**
  22. * Get memory by used info
  23. *
  24. * @ Return int [] Result
  25. * Result. Length = 4; int [0] = memtotal; int [1] = memfree; int [2] = swaptotal; int [3] = swapfree;
  26. * @ Throws ioexception
  27. * @ Throws interruptedexception
  28. */
  29. Public void run (){
  30. // TODO Auto-generated method stub
  31. While (true ){
  32. Try {
  33. Exec ();
  34. Thread. sleep (config. getThreadTime ());
  35. } Catch (Exception e ){
  36. // TODO Auto-generated catch block
  37. Log. error ("Performance Monitoring error:" + e. getMessage ());
  38. E. printstacktrace ();
  39. }
  40. }
  41. }
  42. Public void exec () throws exception {
  43. // Serverstatus Ss = new serverstatus ();
  44. Inetaddress Inet = inetaddress. getlocalhost ();
  45. System. Out. println ("performance monitoring IP:" + inet. tostring ());
  46. String IP = inet. tostring (). substring (inet. tostring (). indexof ("/") + 1 );
  47. Log.info ("performance monitoring IP:" + IP );
  48. Int [] meminfo = linuxsystemtool. getmeminfo ();
  49. System. Out. println ("memtotal:" + meminfo [0]);
  50. System. Out. println ("memfree:" + meminfo [1]);
  51. Snmputil util = new snmputil ();
  52. Util. setcpu (getcpuinfo ());
  53. // Util. setdisk (1 );
  54. Util. setmem (meminfo [0]/meminfo [1]);
  55. Util. setip (IP );
  56. }
  57. Public static int [] getMemInfo () throws IOException, InterruptedException {
  58. File file = new File ("/proc/meminfo ");
  59. BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream (file )));
  60. Int [] result = new int [4];
  61. String str = null;
  62. StringTokenizer token = null;
  63. While (str = br. readLine ())! = Null ){
  64. Token = new StringTokenizer (str );
  65. If (! Token. hasMoreTokens ())
  66. Continue;
  67. Str = token. nextToken ();
  68. If (! Token. hasMoreTokens ())
  69. Continue;
  70. If (str. Repeated signorecase ("MemTotal :"))
  71. Result [0] = Integer. parseInt (token. nextToken ());
  72. Else if (str. equalsIgnoreCase ("MemFree :"))
  73. Result [1] = Integer. parseInt (token. nextToken ());
  74. Else if (str. equalsIgnoreCase ("SwapTotal :"))
  75. Result [2] = Integer. parseInt (token. nextToken ());
  76. Else if (str. equalsIgnoreCase ("SwapFree :"))
  77. Result [3] = Integer. parseInt (token. nextToken ());
  78. }
  79. Return result;
  80. }
  81. /**
  82. * Get memory by used info
  83. *
  84. * @ Return float efficiency
  85. * @ Throws IOException
  86. * @ Throws InterruptedException
  87. */
  88. Public static float getCpuInfo () throws IOException, InterruptedException {
  89. File file = new File ("/proc/stat ");
  90. Bufferedreader BR = new bufferedreader (New inputstreamreader (New fileinputstream (File )));
  91. Stringtokenizer token = new stringtokenizer (Br. Readline ());
  92. Token. nexttoken ();
  93. Long user1 = long. parselong (token. nexttoken ());
  94. Long nice1 = long. parselong (token. nexttoken ());
  95. Long sys1 = long. parselong (token. nexttoken ());
  96. Long idle1 = long. parselong (token. nexttoken ());
  97. Thread. Sleep (1000 );
  98. BR = new bufferedreader (New inputstreamreader (New fileinputstream (File )));
  99. Token = new stringtokenizer (Br. Readline ());
  100. Token. nexttoken ();
  101. Long user2 = long. parselong (token. nexttoken ());
  102. Long nice2 = long. parselong (token. nexttoken ());
  103. Long sys2 = long. parselong (token. nexttoken ());
  104. Long idle2 = long. parselong (token. nexttoken ());
  105. Return (float) (user2 + sys2 + nice2)-(user1 + sys1 + nice1 ))
  106. /(Float) (user2 + nice2 + sys2 + idle2)-(user1 + nice1 + sys1 + idle1 ));
  107. }
  108. /**
  109. * Test class
  110. *
  111. * <P>
  112. *
  113. * @ Author
  114. * </P>
  115. * @ Date
  116. */
  117. Public static void main (String [] args) throws Exception {
  118. Int [] meminfo = linuxsystemtool. getmeminfo ();
  119. System. Out. println ("memtotal:" + meminfo [0]);
  120. System. Out. println ("memfree:" + meminfo [1]);
  121. System. Out. println ("swaptotal:" + meminfo [2]);
  122. System. Out. println ("swapfree:" + meminfo [3]);
  123. System. Out. println ("CPU usage:" + linuxsystemtool. getcpuinfo ());
  124. }
  125. }

Note: The original text uses int to save the CPU Count value, which is inappropriate. Conversion Value overflow may occur on servers that run for a long time.

1. CPU

The file "/proc/stat" contains CPU information. Every CPU tick is used in this file. The following numbers indicate user, nice, sys, idle, and iowait. Some versions of kernel do not include iowait. These values indicate where each tick of the CPU is used from the boot to the present. For example:

Cpu0 256279030 0 11832528 1637168262

That is, 256279030 tick is used for user consumption since CPU 0 is started, and 11832528 is used for sys consumption. So if you want to calculate the CPU load per unit time (for example, 1 s), you only need to calculate the difference between the values before and after 1 second by the number of tick per second. Gkrellm is implemented in this way: (200 * (v2-v1)/CPU_TICKS_PER_SECOND) + 1)/2

For example, if you read/proc/stat for the first time, the user value is 256279030; if you read it again after one second, the value is 256289030, the CPU user consumption in this second is: (200 * (256289030-256279030)/CPU_TICKS_PER_SECOND) + 1)/2 = (10000*200/1000000) + 1) /2 = 1%.

2. memory consumption

The file "/proc/meminfo" contains the memory information and swap information. For example:

$ Cat/proc/meminfo

Total: used: free: shared: buffers: cached:
Mem: 1057009664 851668992 205340672 0 67616768 367820800
Swap: 2146787328 164429824 1982357504
MemTotal: 1032236 kB
MemFree: 200528 kB
MemShared: 0 kB
......

However, from the source code of gkrellm, some versions do not have the statistics of the previous two rows, but can only collect data based on the following types of Key: Value.

3. Disk Space

From the source code of gkrellm, this is a very complex data. Disk partition data may be distributed in:/proc/mounts,/proc/diskstats,/proc/partitions, and so on. In addition, if you want to check a specific path, you also need the help of commands such as mount and df. To reduce the trouble, I can directly use the statfs function to obtain this data.

Int statfs (const char * path, struct statfs * buf );

This function only needs to enter the path name to be checked to return the space usage of the partition where the path is located:

Total Space: buf. f_bsize * buf. f_blocks

Free Space: buf. f_bsize * buf. f_bavail

4. Disk I/O

Disk I/O data is also complex. For some versions, see/proc/diskstats, for some versions, see/proc/partitions, and for some versions, I still don't know where to view them ...... However, we can see that the data version is also the same as the CPU, which requires a value every other time. The difference between the two values is the traffic.

5. Network Traffic

Network traffic is also varied, but it can basically be obtained in/proc/net/dev. It also requires two values to take the difference as the traffic value.

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.