下面列出了怎么用com.sun.management.OperatingSystemMXBean的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getProcessCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getProcessCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 获取windows 监控
* https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html
*
* @return 返回cpu占比和内存占比
*/
@Override
public JSONObject getAllMonitor() {
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
JSONObject jsonObject = new JSONObject();
double total = operatingSystemMXBean.getTotalPhysicalMemorySize();
double free = operatingSystemMXBean.getFreePhysicalMemorySize();
jsonObject.put("memory", String.format("%.2f", (total - free) / total * 100));
//最近系统cpu使用量
double systemCpuLoad = operatingSystemMXBean.getSystemCpuLoad();
if (systemCpuLoad <= 0) {
systemCpuLoad = 0;
}
jsonObject.put("cpu", String.format("%.2f", systemCpuLoad * 100));
jsonObject.put("disk", getHardDisk());
return jsonObject;
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getProcessCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getProcessCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
@Override
public void run() {
stopwatch = Stopwatch.createStarted();
localCpuUsage =
new TimeSeries(
/* startTimeMillis= */ stopwatch.elapsed().toMillis(), BUCKET_DURATION.toMillis());
OperatingSystemMXBean bean =
(OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
Duration previousElapsed = stopwatch.elapsed();
long previousCpuTimeNanos = bean.getProcessCpuTime();
profilingStarted = true;
while (!stopCpuUsage) {
try {
Thread.sleep(LOCAL_CPU_SLEEP_MILLIS);
} catch (InterruptedException e) {
return;
}
Duration nextElapsed = stopwatch.elapsed();
long nextCpuTimeNanos = bean.getProcessCpuTime();
double deltaNanos = nextElapsed.minus(previousElapsed).toNanos();
double cpuLevel = (nextCpuTimeNanos - previousCpuTimeNanos) / deltaNanos;
localCpuUsage.addRange(previousElapsed.toMillis(), nextElapsed.toMillis(), cpuLevel);
previousElapsed = nextElapsed;
previousCpuTimeNanos = nextCpuTimeNanos;
}
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
public synchronized double getCpuUsage() {
if (lastSystemTime == 0) {
baselineCounters();
return 0;
}
long systemTime = System.nanoTime();
long processCpuTime = 0;
if (getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
processCpuTime = ((OperatingSystemMXBean)getOperatingSystemMXBean()).getProcessCpuTime();
}
double cpuUsage = (double)(processCpuTime - lastProcessCpuTime) / (systemTime - lastSystemTime);
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
public static MonitorVo getSysMonitor(){
//jvm
MemoryUsage heapInfo = getHeapInfo();
monitorVo.setJvmHeapInit(decimalFormat.format(heapInfo.getInit() / 1024 / 1024));
monitorVo.setJvmHeapMax(decimalFormat.format(heapInfo.getMax() / 1024 / 1024));
monitorVo.setJvmHeapUsed(decimalFormat.format(heapInfo.getUsed() / 1024 / 1024));
monitorVo.setJvmHeapCommitted(decimalFormat.format(heapInfo.getCommitted() / 1024 / 1024));
MemoryUsage noHeapInfo = getNoHeapInfo();
monitorVo.setJvmNonHeapInit(decimalFormat.format(noHeapInfo.getInit() / 1024 / 1024));
monitorVo.setJvmNonHeapMax(decimalFormat.format(noHeapInfo.getMax() / 1024 / 1024));
monitorVo.setJvmNonHeapUsed(decimalFormat.format(noHeapInfo.getUsed() / 1024 / 1024));
monitorVo.setJvmNonHeapCommitted(decimalFormat.format(noHeapInfo.getCommitted() / 1024 / 1024));
//系统信息
monitorVo.setCpuUseRate(decimalFormat.format(getCpuUsage() * 100));
OperatingSystemMXBean memoryUsage = getMemoryUsage();
monitorVo.setRamTotal(decimalFormat.format(memoryUsage.getTotalPhysicalMemorySize() / 1024 / 1024 / 1024));
monitorVo.setRamUsed(decimalFormat.format((memoryUsage.getTotalPhysicalMemorySize() - memoryUsage.getFreePhysicalMemorySize()) / 1024 / 1024 / 1024));
HashMap<String, Double> diskUsage = getDiskUsage();
monitorVo.setDiskTotal(decimalFormat.format(diskUsage.get("total")));
monitorVo.setDiskUsed(decimalFormat.format(diskUsage.get("used")));
return monitorVo;
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getProcessCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getProcessCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
private UsageUtil getMachineUsage() {
OperatingSystemMXBean operatingSystemMXBean
= ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
// Returns the amount of free physical memory in bytes.
long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();
// Returns the total amount of physical memory in bytes.
long totalPhysicalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize();
// Returns the "recent cpu usage" for the whole system.
double systemCpuLoad = operatingSystemMXBean.getSystemCpuLoad();
int process = Runtime.getRuntime().availableProcessors();
UsageUtil monitorUtil = new UsageUtil();
monitorUtil.memoryUsed = totalPhysicalMemorySize - freePhysicalMemorySize;
monitorUtil.memoryCapacity = totalPhysicalMemorySize;
monitorUtil.cpuUsed = (long) (process * systemCpuLoad * 100);
monitorUtil.cpuCapacity = process * 100;
return monitorUtil;
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getProcessCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getProcessCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getSystemCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getSystemCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getSystemCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getSystemCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getSystemCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getSystemCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getSystemCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getSystemCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public CartridgeStatistics getCartridgeStatistics() throws IOException {
OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
double totalMemory = (double) (osBean.getTotalPhysicalMemorySize() / MB);
double usedMemory = (double) ((totalMemory - (osBean.getFreePhysicalMemorySize() / MB)));
double loadAvg = (double) osBean.getSystemLoadAverage();
// assume system cores = available cores to JVM
int cores = osBean.getAvailableProcessors();
double memoryConsumption = (usedMemory / totalMemory) * 100;
double loadAvgPercentage = (loadAvg / cores) * 100;
if (log.isDebugEnabled()) {
log.debug("Memory consumption: [totalMemory] " + totalMemory + "Mb [usedMemory] " + usedMemory + "Mb: " + memoryConsumption + "%");
log.debug("Processor consumption: [loadAverage] " + loadAvg + " [cores] " + cores + ": " + loadAvgPercentage + "%");
}
return (new CartridgeStatistics(memoryConsumption, loadAvgPercentage));
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
double load;
for(int i=0; i<10; i++) {
load = mbean.getSystemCpuLoad();
if((load<0.0 || load>1.0) && load != -1.0) {
throw new RuntimeException("getSystemCpuLoad() returns " + load
+ " which is not in the [0.0,1.0] interval");
}
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
public static void main(String... args) throws Exception {
OperatingSystemMXBean bean = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
List<String> failedGetterNames = new ArrayList<String>();
List<String> testedGetterNames = Arrays.asList(
"getTotalSwapSpaceSize", "getFreeSwapSpaceSize",
"getTotalPhysicalMemorySize", "getFreePhysicalMemorySize");
for (String getterName : testedGetterNames) {
Method getter = OperatingSystemMXBean.class.getMethod(getterName);
long value = (Long) getter.invoke(bean);
if (value == MEMORYSTATUS_OVERFLOW) {
failedGetterNames.add(getterName);
}
}
if (!failedGetterNames.isEmpty()) {
throw new AssertionError(failedGetterNames);
}
System.out.println("Test passed.");
}
@Override
public Long getValue() {
OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
return mbean.getTotalPhysicalMemorySize() - mbean.getCommittedVirtualMemorySize();
}
MxBean(Map<String, Counter> counters, RuntimeMXBean runtimeBean, OperatingSystemMXBean osBean,
MemoryMXBean memoryMXBean, ThreadMXBean threadBean, ClassLoadingMXBean classLoadingBean,
List<GarbageCollectorMXBean> gcMxBeans, List<MemoryPoolMXBean> memoryPoolMXBeans) {
this.counters = counters;
this.runtimeBean = runtimeBean;
this.osBean = osBean;
this.memoryMXBean = memoryMXBean;
this.threadBean = threadBean;
this.classLoadingBean = classLoadingBean;
this.gcMxBeans = gcMxBeans;
this.memoryPoolMXBeans = memoryPoolMXBeans;
}
@Override
public int getFreeMemory(){
OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
long totalVirtualMemory = osmxb.getTotalPhysicalMemorySize();
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
Double compare = (freePhysicalMemorySize * 1.0 / totalVirtualMemory) * 100;
return compare.intValue();
}
public static void getVmInfo() throws Exception {
VirtualMachine vm = VirtualMachine.attach(String.valueOf(10248));
// 获得连接地址
Properties properties = vm.getAgentProperties();
String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress");
System.out.println(address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector connector = JMXConnectorFactory.connect(url);
RuntimeMXBean rmxb = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), "java.lang:type=Runtime", RuntimeMXBean.class);
MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
System.out.println(operatingSystemMXBean.getSystemCpuLoad());
MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
Map<String, Object> result = new HashMap<>();
//堆提交内存
result.put("heapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前堆内存
result.put("heapUsedMemory", memoryUsage.getUsed() / KB);
//最大堆大小
result.put("heapMaxMemory", memoryUsage.getMax() / KB);
memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
//非堆提交内存
result.put("nonHeapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前非堆内存
result.put("nonHeapUsedMemory", memoryUsage.getUsed() / KB);
//最大非堆大小
result.put("nonHeapMaxMemory", memoryUsage.getMax() / KB);
System.out.println(result);
vm.detach();
}
public static void getMemInfo() throws Exception {
OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
System.out.println("可供运行进程使用的虚拟内存量:" + mem.getCommittedVirtualMemorySize() / 1024 / 1024 + "M");
System.out.println("总交换空间量:" + mem.getTotalSwapSpaceSize() / 1024 / 1024 + "M");
System.out.println("可用交换空间量:" + mem.getFreeSwapSpaceSize() / 1024 / 1024 + "M");
System.out.println("总物理内存:" + mem.getTotalPhysicalMemorySize() / 1024 / 1024 + "M");
System.out.println("可用物理内存量:" + mem.getFreePhysicalMemorySize() / 1024 / 1024 + "M");
for (int i = 0; i < 1; i++) {
System.out.println("cpu使用率:" + ((int) ((mem.getSystemCpuLoad()) * 100000)) / 1000.0 + "%");
Thread.sleep(10);
}
}
@Override
public List<Metric> collect() {
if (osMxBean == null)
osMxBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
long process = Math.round(osMxBean.getProcessCpuLoad() * 100);
long other = Math.round(osMxBean.getSystemCpuLoad() * 100) - process;
List<Metric> metrics = new ArrayList<>();
metrics.add(new Metric("jvm", "JVM", process));
metrics.add(new Metric("other", "Other", other));
return metrics;
}
private void baselineCounters() {
lastSystemTime = System.nanoTime();
if (getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
lastProcessCpuTime = ((OperatingSystemMXBean)getOperatingSystemMXBean()).getProcessCpuTime();
}
}
/**
* Constructor.
*
* @param healthProperties The maximum physical memory threshold
* @param registry Registry
* @param taskScheduler task scheduler
*/
public GenieCpuHealthIndicator(
@NotNull final HealthProperties healthProperties,
@NotNull final MeterRegistry registry,
@NotNull final TaskScheduler taskScheduler
) {
this(
healthProperties.getMaxCpuLoadPercent(),
healthProperties.getMaxCpuLoadConsecutiveOccurrences(),
(OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(),
registry.summary("genie.cpuLoad"),
taskScheduler
);
}
/**
* Initialize field to store OperatingSystem MXBean.
*/
private static void initOSMBean() {
if (osMBean == null) {
synchronized (GridDebug.class) {
if (osMBean == null)
osMBean = getMBean(OS_BEAN_NAME, OperatingSystemMXBean.class);
}
}
}