码迷,mamicode.com
首页 > 编程语言 > 详细

使用java获取内存信息

时间:2015-07-31 08:55:25      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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

 

使用java获取内存信息

标签:

原文地址:http://www.cnblogs.com/freshier/p/4691103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!