有什么方法可以通过所有 JVM 获取 Java 使用的总 RAM 内存
Is there any way to get total RAM memory in use by Java through all JVMs
是否有任何标准方法来获取 java 使用的总内存大小?
我在 Whosebug 中找到了这个答案:
但是,com.sun.*
包并非在所有 JVM 中都可用。
以下可能有帮助?
Runtime runtime = Runtime.getRuntime();
int mb = 1024 * 1024;
log.info("Heap utilization statistics [MB]\nUsed Memory: {}\nFree Memory: {}\nTotal Memory: {}\nMax Memory: {}",
(runtime.totalMemory() - runtime.freeMemory()) / mb, runtime.freeMemory() / mb,
runtime.totalMemory() / mb, runtime.maxMemory() / mb);
您总是可以使用 ProcessBuilder
执行一些合适的外部程序(如 free -m
)并解析其输出。没有获取 RAM 总量的机制,因为 Java 使用给定的堆。它无法分配超出此范围的内存,因此对于 Java,堆 [=14=] 是 总内存。
遗憾的是,标准中没有这样的功能API。但是您可以以 fail-safe 的方式使用扩展的 API 而无需明确引用 non-standard 包:
public class PhysicalMemory {
public static void main(String[] args) {
String[] attr={ "TotalPhysicalMemorySize", "FreePhysicalMemorySize"};
OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean();
List<Attribute> al;
try {
al = ManagementFactory.getPlatformMBeanServer()
.getAttributes(op.getObjectName(), attr).asList();
} catch (InstanceNotFoundException | ReflectionException ex) {
Logger.getLogger(PhysicalMemory.class.getName()).log(Level.SEVERE, null, ex);
al = Collections.emptyList();
}
for(Attribute a: al) {
System.out.println(a.getName()+": "+a.getValue());
}
}
}
这会打印 TotalPhysicalMemorySize
、FreePhysicalMemorySize
属性的值(如果它们可用),而不管它们是如何实现的或在哪个包中实现的。这在 Java 9 中仍然有效,其中甚至拒绝通过反射访问这些 sun-packages 的尝试。
在没有这些属性的 JRE 上,没有独立于平台的方法来获取它们,但至少,这段代码不会因链接错误而退出,但允许在没有信息的情况下继续。
是否有任何标准方法来获取 java 使用的总内存大小?
我在 Whosebug 中找到了这个答案:
但是,com.sun.*
包并非在所有 JVM 中都可用。
以下可能有帮助?
Runtime runtime = Runtime.getRuntime();
int mb = 1024 * 1024;
log.info("Heap utilization statistics [MB]\nUsed Memory: {}\nFree Memory: {}\nTotal Memory: {}\nMax Memory: {}",
(runtime.totalMemory() - runtime.freeMemory()) / mb, runtime.freeMemory() / mb,
runtime.totalMemory() / mb, runtime.maxMemory() / mb);
您总是可以使用 ProcessBuilder
执行一些合适的外部程序(如 free -m
)并解析其输出。没有获取 RAM 总量的机制,因为 Java 使用给定的堆。它无法分配超出此范围的内存,因此对于 Java,堆 [=14=] 是 总内存。
遗憾的是,标准中没有这样的功能API。但是您可以以 fail-safe 的方式使用扩展的 API 而无需明确引用 non-standard 包:
public class PhysicalMemory {
public static void main(String[] args) {
String[] attr={ "TotalPhysicalMemorySize", "FreePhysicalMemorySize"};
OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean();
List<Attribute> al;
try {
al = ManagementFactory.getPlatformMBeanServer()
.getAttributes(op.getObjectName(), attr).asList();
} catch (InstanceNotFoundException | ReflectionException ex) {
Logger.getLogger(PhysicalMemory.class.getName()).log(Level.SEVERE, null, ex);
al = Collections.emptyList();
}
for(Attribute a: al) {
System.out.println(a.getName()+": "+a.getValue());
}
}
}
这会打印 TotalPhysicalMemorySize
、FreePhysicalMemorySize
属性的值(如果它们可用),而不管它们是如何实现的或在哪个包中实现的。这在 Java 9 中仍然有效,其中甚至拒绝通过反射访问这些 sun-packages 的尝试。
在没有这些属性的 JRE 上,没有独立于平台的方法来获取它们,但至少,这段代码不会因链接错误而退出,但允许在没有信息的情况下继续。