用java獲取並傳出虛擬機系統實時性能參數(1:得到性能參數)

準備構建一個日誌系統,記錄創建的虛擬機的實時性能參數。首先先要獲取系統的性能參數,再將參數發送給服務器端存儲下來。


首先是搜了一個內存參數的代碼(跨平臺可用),略微修改,用的jre6:


import java.io.*;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
public class Tst{
       public static String pt="D:\\abc.txt";
       public Tst(){
       }
       public static void main(String[] args) throws Exception{
              //free和use和total均爲KB
              long free=0;
              long use=0;
              long total=0;
              int kb=1024;
              Runtime rt=Runtime.getRuntime();
              total=rt.totalMemory();
              free=rt.freeMemory();
              use=total-free;
              System.out.println("系統內存已用的空間爲:"+use/kb+"MB");
              System.out.println("系統內存的空閒空間爲:"+free/kb+"MB");
              System.out.println("系統總內存空間爲:"+total/kb+"MB");
              OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
              long physicalFree=osmxb.getFreePhysicalMemorySize()/kb;
              long physicalTotal=osmxb.getTotalPhysicalMemorySize()/kb;
              long physicalUse=physicalTotal-physicalFree;
              String os=System.getProperty("os.name");
              System.out.println("操作系統的版本:"+os);
              System.out.println("系統物理內存已用的空間爲:"+physicalFree+"MB");
              System.out.println("系統物理內存的空閒空間爲:"+physicalUse+"MB");
              System.out.println("總物理內存:"+physicalTotal+"MB");
       // 獲得線程總數
       ThreadGroup parentThread;
        for(parentThread = Thread.currentThread().getThreadGroup(); parentThread
                .getParent() != null; parentThread= parentThread.getParent())
            ;
        int totalThread = parentThread.activeCount();
       System.out.println("獲得線程總數:"+totalThread);
       }    
}

有可能會遇到Access restriction: The type OperatingSystemMXBean is not accessible due to restriction on required library C:\Program Files

 \Java\jre7\lib\rt.jar,不讓用OperatingSystemMXBean,這個是eclipse限制的(我不知道爲什麼不讓訪問這個包,望高手指出),可以在它的設置裏面修改。


Windows -> Preferences -> Java -> Compiler -> Errors/Warnings
Project -> Properties -> Java Compiler -> Errors/Warnings

Locate the "Forbidden reference (access rules)" option under "Deprecated and restricted API" section in the dialog box. This option decides how to handle access rules defined inside Eclipse. By default it is set to "Error" which causes Eclipse to complain about references to any restricted classes. Choosing any other option (Warning or Ignore) will remove these error messages.


對於要得到準確的CPU參數,就要麻煩一些,這裏我們只考慮linux。注意到linux裏有top命令類似於window的任務管理器,而 top -b -n 1 能獲得靜態的信息。考慮java執行腳本來獲得該信息。

參考網上代碼寫一個工具類如下:

package bupt.tx.systemmonitor;

//for Linux

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MySystemMonitor {
	public static double getCpuUsage() throws Exception {
		double cpuUsed = 0;
		double idleUsed = 0.0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;
		
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			int linecount = 0;
			while ((str = in.readLine()) != null) {
				linecount++;
				if (linecount == 3) {
					String[] s = str.split("%");
					String idlestr = s[3];
					String idlestr1[] = idlestr.split(" ");
					idleUsed = Double.parseDouble(idlestr1[idlestr1.length - 1]);
					cpuUsed = 100 - idleUsed;

					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return cpuUsed;
	}

	public static double getMemUsage() throws Exception {
		long memUsed = 0;
		long memTotal = 0;
		double memUsage = 0.0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;
		
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));

			String str = null;
			int linecount = 0;
			while ((str = in.readLine()) != null) {
				linecount++;
				if (linecount == 4) {
					String[] s = str.split("k ");
					String memUsedstr = s[1];
					String memTotalstr = s[0];
					String memUsedstr1[] = memUsedstr.split(" ");
					memUsed = Long.parseLong(memUsedstr1[memUsedstr1.length - 1]);
					String memTotalstr1[] = memTotalstr.split(" ");
					memTotal = Long.parseLong(memTotalstr1[memTotalstr1.length - 1]);					
					memUsage = memUsed * 100 / memTotal;

					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return memUsage;
	}

	public static String getTotalInfo() throws Exception {
		String info = "";
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			int linecount = 0;
			while (++linecount <= 5 && ( str = in.readLine() ) != null) {
				str += "\n";
				info += str;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return info;
	}
}

做一下測試:

package bupt.tx.systemmonitor;

public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try
		{
		  System.out.println(MySystemMonitor.getCpuUsage());
		  System.out.println(MySystemMonitor.getMemUsage());
		  System.out.println(MySystemMonitor.getTotalInfo());
		}
		catch(Exception e)
		{
		  e.printStackTrace();
		}
	}

}

在ubuntu10.10中測試運行可以得到正確結果。


發佈了26 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章