Java 获取系统 CPU 使用率及内存占用率
2020-04-20 11:46:43
Java 可以通过这两个类来获取操作系统的运行时信息:
`OperatingSystemMXBean` 、`Runtime `
部分方法说明请参考 [Oracle 官方文档](https://docs.oracle.com/javase/10/docs/api/com/sun/management/OperatingSystemMXBean.html#method.summary)。
下面贴出整个工具类源码:
```
package com.fiebug.dlog.util;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
/**
* 系统环境工具类
* Ref. https://docs.oracle.com/javase/10/docs/api/com/sun/management/OperatingSystemMXBean.html#method.summary
*/
public class RuntimeUtils {
private static final OperatingSystemMXBean systemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
private static final Runtime runtime = Runtime.getRuntime();
/**
* 获取物理内存总大小
*
* @return
*/
public static long getTotalPhysicalMemorySize() {
return systemMXBean.getTotalPhysicalMemorySize();
}
/**
* 获取物理内存剩余大小
*
* @return
*/
public static long getFreePhysicalMemorySize() {
return systemMXBean.getFreePhysicalMemorySize();
}
/**
* 获取物理内存已使用大小
*
* @return
*/
public static long getUsedPhysicalMemorySize() {
return systemMXBean.getTotalPhysicalMemorySize() - systemMXBean.getFreePhysicalMemorySize();
}
/**
* 获取 Swap 总大小
*
* @return
*/
public static long getTotalSwapSpaceSize() {
return systemMXBean.getTotalSwapSpaceSize();
}
/**
* 获取 Swap 剩余大小
*
* @return
*/
public static long getFreeSwapSpaceSize() {
return systemMXBean.getFreeSwapSpaceSize();
}
/**
* 获取 Swap 已使用大小
*
* @return
*/
public static long getUsedSwapSpaceSize() {
return systemMXBean.getTotalSwapSpaceSize() - systemMXBean.getFreeSwapSpaceSize();
}
/**
* 获取 JVM 最大内存
*
* @return
*/
public static long getJvmMaxMemory() {
return runtime.maxMemory();
}
/**
* 获取 JVM 内存总大小
*
* @return
*/
public static long getJvmTotalMemory() {
return runtime.totalMemory();
}
/**
* 获取 JVM 内存剩余大小
*
* @return
*/
public static long getJvmFreeMemory() {
return runtime.freeMemory();
}
/**
* 获取 JVM 内存已使用大小
*
* @return
*/
public static long getJvmUsedMemory() {
return runtime.totalMemory() - runtime.freeMemory();
}
/**
* 获取系统 CPU 使用率
*
* @return
*/
public static double getSystemCpuLoad() {
return systemMXBean.getSystemCpuLoad();
}
/**
* 获取 JVM 进程 CPU 使用率
*
* @return
*/
public static double getProcessCpuLoad() {
return systemMXBean.getProcessCpuLoad();
}
}
```
分类:编程 关键词:CPU,内存
评论(0) 浏览(5603)