admin 管理员组

文章数量: 1184232


2024年3月13日发(作者:html5css3入门教程)

java获得CPU使用率,系统内存,虚拟机内存等情况(不用JNI)

2009年10月23日 星期五 16:30

在Java中,可以获得总的物理内存、剩余的物理内存、已使用的物理内存等信息,下面例子可以

取得这些信息,并且获得在Windows下的内存使用率。

首先编写一个MonitorInfoBean类,用来装载监控的一些信息,包括物理内存、剩余的物理内

存、已使用的物理内存、内存使用率等字段,该类的代码如下:

package r;

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) {

mory = freeMemory;

}

public long getFreePhysicalMemorySize() {

return freePhysicalMemorySize;

}

public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {

ysicalMemorySize = freePhysicalMemorySize;

}

public long getMaxMemory() {

return maxMemory;

}

public void setMaxMemory(long maxMemory) {

ory = maxMemory;

}

public String getOsName() {

return osName;

}

public void setOsName(String osName) {

= osName;

}

public long getTotalMemory() {

return totalMemory;

}

public void setTotalMemory(long totalMemory) {

emory = totalMemory;

}

public long getTotalMemorySize() {

return totalMemorySize;

}

public void setTotalMemorySize(long totalMemorySize) {

emorySize = totalMemorySize;

}

public int getTotalThread() {

return totalThread;

}

public void setTotalThread(int totalThread) {

hread = totalThread;

}

public long getUsedMemory() {

return usedMemory;

}

public void setUsedMemory(long usedMemory) {

mory = usedMemory;

}

public double getCpuRatio() {

return cpuRatio;

}

public void setCpuRatio(double cpuRatio) {

io = cpuRatio;

}

}

接着编写一个获得当前的监控信息的接口,该类的代码如下所示:

package r;

/**

* 获取系统信息的业务逻辑类接口.

*/

public interface IMonitorService {

/**

* 获得当前的监控对象.

* @return 返回构造好的监控对象

* @throws Exception

*/

public MonitorInfoBean getMonitorInfoBean() throws Exception;

}

该类的实现类MonitorServiceImpl如下所示:

package r;

import edReader;

import ption;

import tream;

import treamReader;

import mberReader;

import Tokenizer;

import mentFactory;

import ingSystemMXBean;

/**

*

* 获取系统信息的业务逻辑实现类.

*

* @author GuoHuang

*/

public class MonitorServiceImpl implements IMonitorService {

private static final int CPUTIME = 30;

private static final int PERCENT = 100;

private static final int FAULTLENGTH = 10;

private static String linuxVersion = null;

/**

* 获得当前的监控对象.

*

* @return 返回构造好的监控对象

* @throws Exception

* @author GuoHuang

*/

public MonitorInfoBean getMonitorInfoBean() throws Exception {

int kb = 1024;

// 可使用内存

long totalMemory = time().totalMemory() / kb;

// 剩余内存

long freeMemory = time().freeMemory() / kb;

// 最大可使用内存

long maxMemory = time().maxMemory() / kb;

OperatingSystemMXBean osmxb = (OperatingSystemMXBean)

ratingSystemMXBean();

// 操作系统

String osName = perty("");

// 总的物理内存

long totalMemorySize = alPhysicalMemorySize() / kb;

// 剩余的物理内存

long freePhysicalMemorySize = ePhysicalMemorySize() / kb;

// 已使用的物理内存

long usedMemory = (alPhysicalMemorySize() - ePhysicalMemorySize()) / kb;

// 获得线程总数

ThreadGroup parentThread;

for (parentThread = tThread().getThreadGroup(); ent() != null; parentThread =

ent());

int totalThread = Count();

double cpuRatio = 0;

if (rCase().startsWith("windows")) {

cpuRatio = RatioForWindows();

} else {

cpuRatio = getCpuRateForLinux();

}

// 构造返回对象

MonitorInfoBean infoBean = new MonitorInfoBean();

eMemory(freeMemory);

ePhysicalMemorySize(freePhysicalMemorySize);

Memory(maxMemory);

ame(osName);

alMemory(totalMemory);

alMemorySize(totalMemorySize);

alThread(totalThread);

dMemory(usedMemory);

Ratio(cpuRatio);

return infoBean;

}

private static double getCpuRateForLinux() {

InputStream is = null;

InputStreamReader isr = null;

BufferedReader brStat = null;

StringTokenizer tokenStat = null;

try {

n("Get usage rate of CUP , linux version: " + linuxVersion);

Process process = time().exec("top -b -n 1");

is = utStream();

isr = new InputStreamReader(is);

brStat = new BufferedReader(isr);

if (("2.4")) {

ne();

ne();

ne();

ne();

tokenStat = new StringTokenizer(ne());

ken();

ken();

String user = ken();

ken();

String system = ken();

ken();

String nice = ken();

n(user + " , " + system + " , " + nice);

user = ing(0, f("%"));

system = ing(0, f("%"));

nice = ing(0, f("%"));

float userUsage = new Float(user).floatValue();

float systemUsage = new Float(system).floatValue();

float niceUsage = new Float(nice).floatValue();

return (userUsage + systemUsage + niceUsage) / 100;

} else {

ne();

ne();

tokenStat = new StringTokenizer(ne());

ken();

ken();

ken();

ken();

ken();

ken();

ken();

String cpuUsage = ken();

n("CPU idle : " + cpuUsage);

Float usage = new Float(ing(0, f("%")));

return (1 - alue() / 100);

}

} catch (IOException ioe) {

n(sage());

freeResource(is, isr, brStat);

return 1;

} finally {

freeResource(is, isr, brStat);

}

}

private static void freeResource(InputStream is, InputStreamReader isr,

BufferedReader br) {

try {

if (is != null)

();

if (isr != null)

();

if (br != null)

();

} catch (IOException ioe) {

n(sage());

}

}

/**

* 获得CPU使用率.

*

* @return 返回cpu使用率

* @author GuoHuang

*/

private double getCpuRatioForWindows() {

try {

String procCmd = ("windir") + " process get

Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount

// 取进程信息

long[] c0 = readCpu(time().exec(procCmd));

(CPUTIME);

long[] c1 = readCpu(time().exec(procCmd));

if (c0 != null && c1 != null) {

long idletime = c1[0] - c0[0];

long busytime = c1[1] - c0[1];

return f(PERCENT * (busytime) / (busytime + idletime)).doubleValue();

} else {

return 0.0;

}

} catch (Exception ex) {

tackTrace();

return 0.0;

}

}

/**

* 读取CPU信息.

* @param proc

* @return

* @author GuoHuang

*/

private long[] readCpu(final Process proc) {

long[] retn = new long[2];

try {

putStream().close();

InputStreamReader ir = new InputStreamReader(utStream());

LineNumberReader input = new LineNumberReader(ir);

String line = ne();

if (line == null || () < FAULTLENGTH) {

return null;

}

int capidx = f("Caption");

int cmdidx = f("CommandLine");

int rocidx = f("ReadOperationCount");

int umtidx = f("UserModeTime");

int kmtidx = f("KernelModeTime");

int wocidx = f("WriteOperationCount");

long idletime = 0;

long kneltime = 0;

long usertime = 0;

while ((line = ne()) != null) {

if (() < wocidx) {

continue;

}

// 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,

// ThreadCount,UserModeTime,WriteOperation

String caption = ing(line, capidx, cmdidx - 1).trim();

String cmd = ing(line, cmdidx, kmtidx - 1).trim();

if (f("") >= 0) {

continue;

}

String s1 = ing(line, kmtidx, rocidx - 1).trim();

String s2 = ing(line, umtidx, wocidx - 1).trim();

if (("System Idle Process") || ("System")) {

if (() > 0)

idletime += f(s1).longValue();

if (() > 0)

idletime += f(s2).longValue();

continue;

}

if (() > 0)

kneltime += f(s1).longValue();

if (() > 0)

usertime += f(s2).longValue();

}

retn[0] = idletime;

retn[1] = kneltime + usertime;

return retn;

} catch (Exception ex) {

tackTrace();

} finally {

try {

utStream().close();

} catch (Exception e) {

tackTrace();

}

}

return null;

}

/**

* 测试方法.

*

* @param args

* @throws Exception

* @author GuoHuang

*/

public static void main(String[] args) throws Exception {

IMonitorService service = new MonitorServiceImpl();

MonitorInfoBean monitorInfo = itorInfoBean();

n("cpu占有率=" + Ratio());

n("可使用内存=" + alMemory());

n("剩余内存=" + eMemory());

n("最大可使用内存=" + Memory());

n("操作系统=" + ame());

n("总的物理内存=" + alMemorySize() + "kb");

n("剩余的物理内存=" + eMemory() + "kb");

n("已使用的物理内存=" + dMemory() + "kb");

n("线程总数=" + alThread() + "kb");

}

}

该实现类中需要用到一个自己编写byte的工具类,该类的代码如下所示:

package r;

/**

* byte操作类.

*/

public class Bytes {

/**

* 由于ing对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,

现调整如下:

*

* @param src 要截取的字符串

* @param start_idx 开始坐标(包括该坐标)

* @param end_idx 截止坐标(包括该坐标)

* @return

*/

public static String substring(String src, int start_idx, int end_idx) {

byte[] b = es();

String tgt = "";

for (int i = start_idx; i <= end_idx; i++) {

tgt += (char) b[i];

}

return tgt;

}

}

运行下MonitorBeanImpl类,读者将会看到当前的内存、cpu利用率等信息。


本文标签: 内存 信息 物理 监控