java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java CPU和内存占用率

Java获取CPU和内存占用率最简单的方法

作者:DCTANT

这篇文章主要介绍了Java获取CPU和内存占用率最简单的方法,文中通过代码示例和图文结合的方式给大家讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下

先上代码,保证这是目前全网最简单的获取系统CPU占用率、内存占用率的方法

    @Test
    public void testSystemUsage() {
        final long GB = 1024 * 1024 * 1024;
        while (true) {
            OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
            String osJson = JSON.toJSONString(operatingSystemMXBean);
//            System.out.println("osJson is " + osJson);
            JSONObject jsonObject = JSON.parseObject(osJson);
            double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
            double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
            Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
            Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
            double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
            double freeMemory = 1.0 * freePhysicalMemorySize / GB;
            double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
 
            StringBuilder result = new StringBuilder();
            result.append("系统CPU占用率: ")
                    .append(twoDecimal(systemCpuLoad))
                    .append("%,内存占用率:")
                    .append(twoDecimal(memoryUseRatio))
                    .append("%,系统总内存:")
                    .append(twoDecimal(totalMemory))
                    .append("GB,系统剩余内存:")
                    .append(twoDecimal(freeMemory))
                    .append("GB,该进程占用CPU:")
                    .append(twoDecimal(processCpuLoad))
                    .append("%");
            System.out.println(result.toString());
 
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    public double twoDecimal(double doubleValue) {
        BigDecimal bigDecimal = new BigDecimal(doubleValue).setScale(2, RoundingMode.HALF_UP);
        return bigDecimal.doubleValue();
    }

这代码我注释都懒得写一行了,主要是这一行:JSON.toJSONString(operatingSystemMXBean),输出的结果如图:(使用的是阿里巴巴的fastjson)

我当时只是为了偷懒一个个去get输出,就直接通过JSON的方式打印输出了,结果不输出不知道,一输出吓一跳,把一堆隐藏字段都给输出出来了,包括systemCpuLoad、processCpuLoad,这两个字段一个就是系统CPU总的利用率,另一个应该是这个Java进程当前的CPU利用率,这样就省去很多事了,直接通过JSONObject取出来就是了,直接就给输出出来了。

其中:OperatingSystemMXBean这个类是JDK自带的,不用引入任何第三方jar包

输出最终结果如下:

上面的方法只能针对JDK8,换成现在模块化的JDK后,OperatingSystemMXBean类就无法反射获取其中的信息了,会导致FastJson报错。当然我已经找到了解决方法。

直接上代码

package com.itdct.justtest.test.monitor;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
 
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.text.DecimalFormat;
 
import lombok.extern.slf4j.Slf4j;
 
/**
 * @author DCTANT
 * @version 1.0
 * @date 2024/3/21 11:21:21
 * @description
 */
@Slf4j
public class MonitorServer {
    private static final long GB = 1024 * 1024 * 1024;
    private static final long MB = 1024 * 1024;
    private static final DecimalFormat decimalFormat = new DecimalFormat("0.0");
 
    public MonitorInfoModel monitor() {
        MonitorInfoModel monitorInfoModel = new MonitorInfoModel();
 
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
 
        long usedHeapMemory = heapMemoryUsage.getUsed();
        long maxHeapMemory = heapMemoryUsage.getMax();
        long usedNonHeapMemory = nonHeapMemoryUsage.getUsed();
        long maxNonHeapMemory = nonHeapMemoryUsage.getMax();
 
        String usedHeapMemoryInfo = decimalFormat.format(1.0 * usedHeapMemory / MB) + "MB";
        String maxHeapMemoryInfo = decimalFormat.format(1.0 * maxHeapMemory / MB) + "MB";
        String usedNonHeapMemoryInfo = decimalFormat.format(1.0 * usedNonHeapMemory / MB) + "MB";
 
        String maxNonHeapMemoryInfo;
        if (maxNonHeapMemory == -1L) {
            maxNonHeapMemoryInfo = "-";
        } else {
            maxNonHeapMemoryInfo = decimalFormat.format(1.0 * maxNonHeapMemory / MB) + "MB";
        }
        monitorInfoModel.setUsedHeapMemoryInfo(usedHeapMemoryInfo);
        monitorInfoModel.setMaxHeapMemoryInfo(maxHeapMemoryInfo);
        monitorInfoModel.setUsedNonHeapMemoryInfo(usedNonHeapMemoryInfo);
        monitorInfoModel.setMaxNonHeapMemoryInfo(maxNonHeapMemoryInfo);
 
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        if (operatingSystemMXBean instanceof com.sun.management.OperatingSystemMXBean) {
            com.sun.management.OperatingSystemMXBean opBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;
            double cpuLoad = opBean.getCpuLoad();
            String cpuLoadInfo = decimalFormat.format(cpuLoad * 100) + "%";
            monitorInfoModel.setCpuLoadInfo(cpuLoadInfo);
 
            double processCpuLoad = opBean.getProcessCpuLoad();
            String processCpuLoadInfo = decimalFormat.format(processCpuLoad * 100) + "%";
            monitorInfoModel.setProcessCpuLoadInfo(processCpuLoadInfo);
 
            long totalMemorySize = opBean.getTotalMemorySize();
            long freeMemorySize = opBean.getFreeMemorySize();
 
            String totalMemoryInfo = decimalFormat.format(1.0 * totalMemorySize / GB) + "GB";
            String freeMemoryInfo = decimalFormat.format(1.0 * freeMemorySize / GB) + "GB";
            String useMemoryInfo = decimalFormat.format(1.0 * (totalMemorySize - freeMemorySize) / GB) + "GB";
            String memoryUseRatioInfo = decimalFormat.format((1.0 * (totalMemorySize - freeMemorySize) / totalMemorySize * 100)) + "%";
            monitorInfoModel.setTotalMemoryInfo(totalMemoryInfo);
            monitorInfoModel.setFreeMemoryInfo(freeMemoryInfo);
            monitorInfoModel.setUseMemoryInfo(useMemoryInfo);
            monitorInfoModel.setMemoryUseRatioInfo(memoryUseRatioInfo);
 
            long freeSwapSpaceSize = opBean.getFreeSwapSpaceSize();
            long totalSwapSpaceSize = opBean.getTotalSwapSpaceSize();
 
            String freeSwapSpaceInfo = decimalFormat.format(1.0 * freeSwapSpaceSize / GB) + "GB";
            String totalSwapSpaceInfo = decimalFormat.format(1.0 * totalSwapSpaceSize / GB) + "GB";
            String useSwapSpaceInfo = decimalFormat.format(1.0 * (totalSwapSpaceSize - freeSwapSpaceSize) / GB) + "GB";
            String swapUseRatioInfo = decimalFormat.format((1.0 * (totalSwapSpaceSize - freeSwapSpaceSize) / totalSwapSpaceSize * 100)) + "%";
            monitorInfoModel.setFreeSwapSpaceInfo(freeSwapSpaceInfo);
            monitorInfoModel.setTotalSwapSpaceInfo(totalSwapSpaceInfo);
            monitorInfoModel.setUseSwapSpaceInfo(useSwapSpaceInfo);
            monitorInfoModel.setSwapUseRatioInfo(swapUseRatioInfo);
 
            String arch = opBean.getArch();
            String name = opBean.getName();
            monitorInfoModel.setArch(arch);
            monitorInfoModel.setName(name);
        }
        return monitorInfoModel;
    }
 
    public static void main(String[] args) throws InterruptedException {
        MonitorServer monitorServer = new MonitorServer();
        while (true) {
            MonitorInfoModel infoModel = monitorServer.monitor();
//        String jsonString = JSON.toJSONString(infoModel, SerializerFeature.PrettyFormat);
//        log.info(jsonString);
            log.info("""
                        堆内存使用情况:
                        使用中的堆内存:{}
                        最大堆内存:{}
                        使用中的非堆内存:{}
                        最大非堆内存:{}
                        """,
                    infoModel.getUsedHeapMemoryInfo(),
                    infoModel.getMaxHeapMemoryInfo(),
                    infoModel.getUsedNonHeapMemoryInfo(),
                    infoModel.getMaxNonHeapMemoryInfo());
 
            log.info("""
                        系统信息:
                        系统架构:{}
                        系统名称:{}
                        系统使用情况:
                        CPU使用率:{}
                        JVM进程CPU使用率:{}
                        系统总内存:{}
                        使用中的内存:{}
                        内存使用率:{}
                        系统总交换内存:{}
                        使用中的交换内存:{}
                        交换内存使用率:{}
                        """,
                    infoModel.getArch(),
                    infoModel.getName(),
                    infoModel.getCpuLoadInfo(),
                    infoModel.getProcessCpuLoadInfo(),
                    infoModel.getTotalMemoryInfo(),
                    infoModel.getUseMemoryInfo(),
                    infoModel.getMemoryUseRatioInfo(),
                    infoModel.getTotalSwapSpaceInfo(),
                    infoModel.getUseSwapSpaceInfo(),
                    infoModel.getSwapUseRatioInfo());
 
            Thread.sleep(1000);
        }
 
    }
}

核心代码自然是这句:

  if (operatingSystemMXBean instanceof com.sun.management.OperatingSystemMXBean) {
            com.sun.management.OperatingSystemMXBean opBean = (com.sun.management.OperatingSystemMXBean) operatingSystemMXBean;

将java.lang.management.OperatingSystemMXBean转为com.sun.management.OperatingSystemMXBean,即可获取系统运行信息

其中MonitorInfoModel类为:

package com.itdct.justtest.test.monitor;
 
import lombok.Data;
 
/**
 * @author DCTANT
 * @version 1.0
 * @date 2024/3/21 11:21:36
 * @description
 */
@Data
public class MonitorInfoModel {
    // INFO: DCTANT: 2024/3/21 JVM堆信息
    /**
     * 使用中的堆内存信息
     */
    private String usedHeapMemoryInfo;
 
    /**
     * 最大堆内存信息
     */
    private String maxHeapMemoryInfo;
 
    /**
     * 使用中的非堆内存信息
     */
    private String usedNonHeapMemoryInfo;
 
    /**
     * 最大非堆内存信息
     */
    private String maxNonHeapMemoryInfo;
 
    // INFO: DCTANT: 2024/3/21 计算机信息
    /**
     * 系统cpu使用率信息
     */
    private String cpuLoadInfo;
 
    /**
     * JVM进程 cpu使用率信息
     */
    private String processCpuLoadInfo;
 
    /**
     * 系统总内存信息
     */
    private String totalMemoryInfo;
 
    /**
     * 系统空闲内存信息
     */
    private String freeMemoryInfo ;
 
    /**
     * 使用中的内存信息
     */
    private String useMemoryInfo ;
 
    /**
     * 内存使用率
     */
    private String memoryUseRatioInfo;
 
    /**
     * 空闲交换内存信息
     */
    private String freeSwapSpaceInfo;
 
    /**
     * 总交换内存信息
     */
    private String totalSwapSpaceInfo;
 
    /**
     * 使用中交换内存信息
     */
    private String useSwapSpaceInfo;
 
    /**
     * 交换内存使用率信息
     */
    private String swapUseRatioInfo;
 
    /**
     * 系统架构
     */
    private String arch;
 
    /**
     * 系统名称
     */
    private String name;
 
 
}

封装之后返回,直接就能使用,非常优雅

运行效果

以上就是Java获取CPU和内存占用率最简单的方法的详细内容,更多关于Java CPU和内存占用率的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文