文件名 ByteConverter.java
用于将字节数值转为 MB数值
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* <h2>字节数值转换</h2>
* <p>
*
* </p>
*
* @author
* @since
**/
public class ByteConverter {
/**
* 将字节数量转换为MB
*
* @param bytes 字节数量
* @return 对应的MB
*/
public static BigDecimal bytesToMB(double bytes) {
BigDecimal bytesConver = BigDecimal.valueOf(bytes);
// 字节数量转换MB = 字节数 / (1024 * 1024)
BigDecimal conditions = BigDecimal.valueOf(1048576L);
return bytesConver.divide(conditions, 2, RoundingMode.HALF_UP);
}
}
import java.math.BigDecimal;
import java.math.RoundingMode;
import cn.hutool.core.lang.Singleton;
/**
* <h2>JVM运行信息</h2>
* <p>
*
* </p>
*
* @author
* @since
**/
public class JvmInfo {
/**
* 单例模式,使用 hutool工具,也可以自己实现,也可以直接不用单例模式 直接new
*/
private static JvmInfo info = Singleton.get(JvmInfo.class);
/**
* JVM已用内存
*/
private BigDecimal usedMemory;
/**
* JVM最大可用内存
*/
private BigDecimal maxMemory;
/**
* JVM剩余内存
*/
private BigDecimal freeMemory;
/**
* jdk安装路径
*/
private String jdkHome;
/**
* jdk版本
*/
private String jdkVersion;
/**
* JVM内存使用率
*/
private BigDecimal usage;
private JvmInfo(){}
public static JvmInfo getInstans() {
Runtime runtime = Runtime.getRuntime();
info.setUsedMemory(ByteConverter.bytesToMB(runtime.totalMemory() - runtime.freeMemory()));
info.setMaxMemory(ByteConverter.bytesToMB(Runtime.getRuntime().maxMemory()));
info.setFreeMemory(ByteConverter.bytesToMB(Runtime.getRuntime().freeMemory()));
info.setUsage(info.getUsedMemory().divide(info.getMaxMemory(), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
info.setJdkVersion(System.getProperty("java.version"));
info.setJdkHome(System.getProperty("java.home"));
return info;
}
public String getJdkVersion() {
return jdkVersion;
}
public void setJdkVersion(String jdkVersion) {
this.jdkVersion = jdkVersion;
}
public BigDecimal getUsage() {
return usage;
}
public void setUsage(BigDecimal usage) {
this.usage = usage;
}
public BigDecimal getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(BigDecimal usedMemory) {
this.usedMemory = usedMemory;
}
public BigDecimal getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(BigDecimal maxMemory) {
this.maxMemory = maxMemory;
}
public BigDecimal getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(BigDecimal freeMemory) {
this.freeMemory = freeMemory;
}
public String getJdkHome() {
return jdkHome;
}
public void setJdkHome(String jdkHome) {
this.jdkHome = jdkHome;
}
}
public static void main(String[] args) {
System.out.printf("JVM运行信息:%s", JvmInfo.getInstans());
}