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程序获取JVM与宿主机内存使用状态
最新推荐文章于 2025-02-19 22:11:14 发布
该代码段定义了一个名为SystemUtils的类,包含两个静态方法:printMemoryInfoJVM和printMemoryInfoHost。前者用于获取并打印JVM的总内存、最大内存、空闲内存以及内存使用率,后者则用于获取主机的总物理内存、空闲物理内存和主机内存使用率。通过日志记录这些信息,可以用于系统性能监控。
5279

被折叠的 条评论
为什么被折叠?



