(轉)用Java獲得當前性能信息

(轉)用Java獲得當前性能信息
http://www.blogjava.net/amigoxie/archive/2008/04/30/197564.html
在Java中,可以獲得總的物理內存、剩余的物理內存、已使用的物理內存等信息,本例講解如何取得這些信息,并且獲得在Windows下的內存使用率。
???? 首先編寫一個MonitorInfoBean類,用來裝載監控的一些信息,包括物理內存、剩余的物理內存、已使用的物理內存、內存使用率等字段,該類的代碼如下:
package?com.amigo.performance;

/**?*//**
?*?監視信息的JavaBean類.
?*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?*?
@version?1.0?
?*?Creation?date:?2008-4-25?-?上午10:37:00
?
*/

public?class?MonitorInfoBean?{
????
/**?*//**?可使用內存.?*/
????
private?long?totalMemory;
????
????
/**?*//**?剩余內存.?*/
????
private?long?freeMemory;
????
????
/**?*//**?最大可使用內存.?*/
????
private?long?maxMemory;
????
????
/**?*//**?操作系統.?*/
????
private?String?osName;
????
????
/**?*//**?總的物理內存.?*/
????
private?long?totalMemorySize;
????
????
/**?*//**?剩余的物理內存.?*/
????
private?long?freePhysicalMemorySize;
????
????
/**?*//**?已使用的物理內存.?*/
????
private?long?usedMemory;
????
????
/**?*//**?線程總數.?*/
????
private?int?totalThread;
????
????
/**?*//**?cpu使用率.?*/
????
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;
????}

}

???? 接著編寫一個獲得當前的監控信息的接口,該類的代碼如下所示:
package?com.amigo.performance;

/**?*//**
?*?獲取系統信息的業務邏輯類接口.
?*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?*?
@version?1.0?
?*?Creation?date:?2008-3-11?-?上午10:06:06
?
*/
public?interface?IMonitorService?{
????
/**?*//**
?????*?獲得當前的監控對象.
?????*?
@return?返回構造好的監控對象
?????*?
@throws?Exception
?????*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?????*?Creation?date:?2008-4-25?-?上午10:45:08
?????
*/

????
public?MonitorInfoBean?getMonitorInfoBean()?throws?Exception;

}
???? 該類的實現類MonitorServiceImpl如下所示:
package?com.amigo.performance;

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

import?sun.management.ManagementFactory;

import?com.sun.management.OperatingSystemMXBean;

/**?*//**
?*?獲取系統信息的業務邏輯實現類.
?*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?*?
@version?1.0?Creation?date:?2008-3-11?-?上午10:06:06
?
*/

public?class?MonitorServiceImpl?implements?IMonitorService?{
????
????
private?static?final?int?CPUTIME?=?30;

????
private?static?final?int?PERCENT?=?100;

????
private?static?final?int?FAULTLENGTH?=?10;

????
/**?*//**
?????*?獲得當前的監控對象.
?????*?
@return?返回構造好的監控對象
?????*?
@throws?Exception
?????*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?????*?Creation?date:?2008-4-25?-?上午10:45:08
?????
*/

????
public?MonitorInfoBean?getMonitorInfoBean()?throws?Exception?{
????????
int?kb?=?1024;
????????
????????
//?可使用內存
????????long?totalMemory?=?Runtime.getRuntime().totalMemory()?/?kb;
????????
//?剩余內存
????????long?freeMemory?=?Runtime.getRuntime().freeMemory()?/?kb;
????????
//?最大可使用內存
????????long?maxMemory?=?Runtime.getRuntime().maxMemory()?/?kb;

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

????????
//?操作系統
????????String?osName?=?System.getProperty("os.name");
????????
//?總的物理內存
????????long?totalMemorySize?=?osmxb.getTotalPhysicalMemorySize()?/?kb;
????????
//?剩余的物理內存
????????long?freePhysicalMemorySize?=?osmxb.getFreePhysicalMemorySize()?/?kb;
????????
//?已使用的物理內存
????????long?usedMemory?=?(osmxb.getTotalPhysicalMemorySize()?-?osmxb
????????????????.getFreePhysicalMemorySize())
????????????????
/?kb;

????????
//?獲得線程總數
????????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();
????????}

????????
????????
//?構造返回對象
????????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;
????}


????
/**?*//**
?????*?獲得CPU使用率.
?????*?
@return?返回cpu使用率
?????*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?????*?Creation?date:?2008-4-25?-?下午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";
????????????
//?取進程信息
????????????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;
????????}

????}


????
/**?*//**
?????*?讀取CPU信息.
?????*?
@param?proc
?????*?
@return
?????*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?????*?Creation?date:?2008-4-25?-?下午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;
????????????????}

????????????????
//?字段出現順序: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;
????}

????
????
/**?*//**
?????*?測試方法.
?????*?
@param?args
?????*?
@throws?Exception
?????*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?????*?Creation?date:?2008-4-30?-?下午04:47:29
?????
*/

????
public?static?void?main(String[]?args)?throws?Exception?{
????????IMonitorService?service?
=?new?MonitorServiceImpl();
????????MonitorInfoBean?monitorInfo?
=?service.getMonitorInfoBean();
????????System.out.println(
"cpu占有率="?+?monitorInfo.getCpuRatio());
????????
????????System.out.println(
"可使用內存="?+?monitorInfo.getTotalMemory());
????????System.out.println(
"剩余內存="?+?monitorInfo.getFreeMemory());
????????System.out.println(
"最大可使用內存="?+?monitorInfo.getMaxMemory());
????????
????????System.out.println(
"操作系統="?+?monitorInfo.getOsName());
????????System.out.println(
"總的物理內存="?+?monitorInfo.getTotalMemorySize()?+?"kb");
????????System.out.println(
"剩余的物理內存="?+?monitorInfo.getFreeMemory()?+?"kb");
????????System.out.println(
"已使用的物理內存="?+?monitorInfo.getUsedMemory()?+?"kb");
????????System.out.println(
"線程總數="?+?monitorInfo.getTotalThread()?+?"kb");
????}

}

??????? 該實現類中需要用到一個自己編寫byte的工具類,該類的代碼如下所示:
package?com.amigo.performance;

/**?*//**
?*?byte操作類.
?*?
@author?<a?href="mailto:xiexingxing1121@126.com">AmigoXie</a>
?*?
@version?1.0?
?*?Creation?date:?2008-4-30?-?下午04:57:23
?
*/

public?class?Bytes?{
????
/**?*//**
?????*?由于String.subString對漢字處理存在問題(把一個漢字視為一個字節),因此在
?????*?包含漢字的字符串時存在隱患,現調整如下:
?????*?
@param?src?要截取的字符串
?????*?
@param?start_idx?開始坐標(包括該坐標)
?????*?
@param?end_idx???截止坐標(包括該坐標)
?????*?
@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;
????}

}

??????? 運行下MonitorBeanImpl類,讀者將會看到當前的內存、cpu利用率等信息。
posted on 2008-05-02 07:03 jackyrong的世界 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/jackyrong/archive/2008/05/02/1179180.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/276905.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/276905.shtml
英文地址,請注明出處:http://en.pswp.cn/news/276905.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

docker wsl2啟動不了_Docker學習筆記

在筆記本上主要還是想以輕量、方便為主&#xff0c;所以采用的是在WSL2中使用docker的這么一個方案。WSL2我筆記本原來是預裝的是WIN10家庭版&#xff0c;需要先升級為專業版&#xff0c;并加入windows預覽體驗計劃。更新完之后&#xff0c;安裝WSL&#xff0c;我選擇的是Ubunt…

暑假集訓-8.06總結

學習內容&#xff1a; 搜索 今日完成題數&#xff08;不包含多校&#xff09;&#xff1a;4 今日看書情況&#xff1a;15頁 今日心得&#xff1a; 今天學的是搜索&#xff0c;雖然以前學過&#xff0c;但書上講的更具體些&#xff0c; 比如說如何去優化搜索的次數等 英語題目好…

網易馬進:DDB從分布式數據庫到結構化數據中心的架構變遷

導語&#xff1a; 本文根據馬進老師在2018年5月10日【第九屆中國數據庫技術大會(DTCC)】現場演講內容整理而成。馬進 網易 DDB項目負責人來自網易杭研大數據平臺組&#xff0c;入職以來先后參與了分布式數據庫DDB&#xff0c;緩存NKV&#xff0c;網易數據運河NDC等項目&#xf…

element label動態賦值_淺析 vuerouter 源碼和動態路由權限分配

背景上月立過一個 flag&#xff0c;看完 vue-router 的源碼&#xff0c;可到后面逐漸發現 vue-router 的源碼并不是像很多總結的文章那么容易理解&#xff0c;閱讀過你就會發現里面的很多地方都會有多層的函數調用關系&#xff0c;還有大量的 this 指向問題&#xff0c;而且會有…

MessagePack Java 0.6.X List, Map 對象的序列化和反序列化

為了序列化原生的容器對象例如 List 和 Map 對象&#xff0c;你必須使用 Template。 Template 對象是 serializer 和 deserializer 的配對。例如&#xff0c;為了序列化一個 List 對象&#xff0c;在 List 對象中 Integer 對象為元素&#xff0c;你可以使用下面的方法來創建一…

世界領先的界面設計公司:The Skins Factory

該公司的網站&#xff1a; http://www.theskinsfactory.com/skinsfactory/ 該公司誕生于2000年&#xff0c;由一群狂熱的界面愛好者&#xff0c;帶著對GUI的熱情和大膽的洞察力創立。很快&#xff0c;皮膚工廠便成長為世界領先的、真正的、革命性界面解決方案提供商。 更多的精…

HDU 1253 勝利大逃亡 題解

勝利大逃亡 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 44540 Accepted Submission(s): 15483 Problem DescriptionIgnatius被魔王抓走了,有一天魔王出差去了,這可是Ignatius逃亡的好機會.魔王住在一個城堡…

lstm需要優化的參數_使用PyTorch手寫代碼從頭構建LSTM,更深入的理解其工作原理...

這是一個造輪子的過程&#xff0c;但是從頭構建LSTM能夠使我們對體系結構進行更加了解&#xff0c;并將我們的研究帶入下一個層次。LSTM單元是遞歸神經網絡深度學習研究領域中最有趣的結構之一&#xff1a;它不僅使模型能夠從長序列中學習&#xff0c;而且還為長、短期記憶創建…

有哪些漂亮的中國風 LOGO 設計?

提到中國風的logo&#xff0c;我覺得首先登場的應該是北京故宮博物院的logo&#xff0c;鐺&#xff01;故宮博物院的logo&#xff0c;從顏色&#xff0c;到外形&#xff0c;到元素&#xff0c;無一例外&#xff0c;充滿了中國風的味道&#xff0c;可謂是中國風中的典型。同一風…

大家放松下,仿《大腕》經典對白

仿《大腕》經典對白&#xff1a; 一定要找那最流行的框架&#xff0c; 用功能最強大編輯器&#xff0c; 做就要做最復雜的系統&#xff0c; 輕量級的絕對不行&#xff0c; 框架最簡單也得是&#xff33;&#xff30;&#xff32;&#xff29;&#xff2e;&#xff27;&…

MySQL-8.0.12源碼安裝實例

1、通過官網下載對應的版本后&#xff0c;通過FTP上傳至云服務器的/usr/local/src 目錄 2、解壓縮文件 [rootJSH-01 src]# ls mysql-boost-8.0.12.tar.gz [rootJSH-01 src]# tar zxvf mysql-boost-8.0.12.tar.gz [rootJSH-01 src]# ls mysql-8.0.12 mysql-boost-8.0.12.tar.gz…

python3常用模塊_Python3 常用模塊

一、time與datetime模塊 在Python中&#xff0c;通常有這幾種方式來表示時間&#xff1a; 時間戳(timestamp)&#xff1a;通常來說&#xff0c;時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”&#xff0c;返回的是float類型。 格式…

Windows下的HEAP溢出及其利用

Windows下的HEAP溢出及其利用 作者: isno 一、概述 前一段時間ASP的溢出鬧的沸沸揚揚&#xff0c;這個漏洞并不是普通的堆棧溢出&#xff0c;而是發生在HEAP中的溢出&#xff0c;這使大家重新認識到了Windows下的HEAP溢出的可利用性。其實WIN下的HEAP溢出比Linux和SOLARIS下面的…

地方政府不愿房價下跌 救市或化解房地產調控

地方政府不愿房價下跌 "救市"或化解房地產調控 2008年05月09日 07:29:38  來源&#xff1a;上海證券報 漫畫 劉道偉 由于房地產業與地方政府利益攸關&#xff0c;地方政府最不愿意看到房價下跌。中央房地產調控政策剛剛導致部分城市的房價步入調整&#xff0c;一些…

App移動端性能工具調研

使用GT的差異化場景平臺描述release版本development版本Android在Android平臺上&#xff0c;如果希望使用GT的高級功能&#xff0c;如“插樁”等&#xff0c;就必須將GT的SDK嵌入到被調測的應用的工程里&#xff0c;再配合安裝好的GT使用。支持AndroidiOS在iOS平臺上&#xff0…

UITabBar Contoller

。UITabBar中的UIViewController獲得控制權&#xff1a;在TabBar文件中添加&#xff1a;IBOutlet UITabBar *myTabBar; //在xib中連接tabBar&#xff1b;(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:      (UIViewControlle…

python3.5安裝pip_win10上python3.5.2第三方庫安裝(運用pip)

1 首先在python官網下載并安裝python。我這兒用的是python3.5.2&#xff0c;其自帶了pip。如果你選擇的版本沒有自帶pip&#xff0c;那么請查找其他的安裝教程。 2 python安裝好以后&#xff0c;我在其自帶的命令提示符窗口中輸入了pip&#xff0c;結果尷尬了&#xff0c;提示我…

C語言程序設計 練習題參考答案 第八章 文件(2)

/* 8.&#xff18;從文件ex88_1.txt中取出成績&#xff0c;排序后&#xff0c;按降序存放EX88_2.TXT中 */ #include "stdio.h" #define N 10 struct student { int num; char name[20]; int score[3]; /*不能使用float*/ float average; }; void sort(struc…

語法上的小trick

語法上的小trick 構造函數 雖然不寫構造函數也是可以的&#xff0c;但是可能會開翻車&#xff0c;所以還是寫上吧。&#xff1a; 提供三種寫法&#xff1a; ? 使用的時候只用&#xff1a; 注意&#xff0c;這里的A[i]gg(3,3,3)的“gg”不能打括號&#xff0c;否則就是強制轉換…

Ubuntu18.04如何讓桌面軟件默認root權限運行?

什么是gksu? 什么是gksu:Linxu中的gksu是系統中的su/sudo工具,如果安裝了gksu,在終端中鍵入gksu會彈出一個對話框. 安裝gksu: 在Ubuntu之前的版本中是繼承gksu工具的,但是在Ubutu18.04中并沒有集成, 在Elementary OS中連gksu的APT源都沒有. Ubuntu18.04 安裝和使用gksu: seven…