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)+"%");
}
}
}```
文章来源地址https://www.toymoban.com/news/detail-600927.html
文章来源:https://www.toymoban.com/news/detail-600927.html
到了这里,关于java程序获取JVM与宿主机内存使用状态的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!