java程序获取JVM与宿主机内存使用状态

        
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SystemUtils {

//获取JVM内存状态
    static public void printMemoryInfoJVM(){
        try{
        double allocatedMemory = (double)Runtime.getRuntime().totalMemory()/1024./1024./1024.;
        double maxMemory = (double)Runtime.getRuntime().maxMemory()/1024./1024./1024.;
        double freeMemory =  (double)Runtime.getRuntime().freeMemory()/1024./1024./1024.;
        freeMemory += (maxMemory - allocatedMemory); 
        double memoryUsage = (maxMemory - freeMemory)/maxMemory;
        log.info("JVM Allocated Memory:"+String.format("%.2f",allocatedMemory)+"G");
        log.info("JVM Max Memory:"+String.format("%.2f",maxMemory)+"G");
        log.info("JVM Free Memory:"+String.format("%.2f",freeMemory)+"G");
        log.info("JVM Memory Usage:"+String.format("%.2f",memoryUsage*100)+"%");
    }
//获取宿主机内存状态
    static public void printMemoryInfoHost(){
            OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            double totalMemorySystem = (double)mem.getTotalPhysicalMemorySize() / 1024. / 1024. /1024.;
            double freeMemorySystem = (double)mem.getFreePhysicalMemorySize() / 1024. / 1024. /1024.;
            double memoryUsageSystem = (totalMemorySystem - freeMemorySystem)/totalMemorySystem;
            log.info("Host Total Memory:"+String.format("%.2f",totalMemorySystem)+"G");
            log.info("Host Free Memory:"+String.format("%.2f",freeMemorySystem)+"G");
            log.info("Host Memory Usage:"+String.format("%.2f",memoryUsageSystem*100)+"%");
    }
}

    }```

你可能感兴趣的:(java学习,java,jvm,开发语言)