java 以编程方式检查可用的堆大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6487802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check available heapSize programmatically?
提问by Johnydep
I am using Eclipse. The problem is my application crashes if the allocated memory is less then 512MB. Now is there anyway to check the available memory for a program before starting heavy memory exhaustive processing? For example, I know we can check available JVM heap size as:
我正在使用 Eclipse。问题是如果分配的内存小于 512MB,我的应用程序就会崩溃。现在有没有在开始大量内存穷举处理之前检查程序的可用内存?例如,我知道我们可以检查可用的 JVM 堆大小为:
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
Problem is, this gives the JVM heap size. Even increasing it does not work using Eclipse. In Eclipse, if I change the VM arguments then it works. However the printout from above statements is always the same. Is there any command through which I can exactly know how much memory I am allocated for a particular application?
问题是,这给出了 JVM 堆大小。即使增加它也不能使用 Eclipse。在 Eclipse 中,如果我更改 VM 参数,则它可以工作。但是,上述语句的打印输出始终相同。是否有任何命令可以让我确切地知道为特定应用程序分配了多少内存?
回答by Mike Lue
You could use JMXto collect the usage of heap memory at runtime.
您可以使用JMX来收集运行时堆内存的使用情况。
Code Example:
代码示例:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) {
if (mpBean.getType() == MemoryType.HEAP) {
System.out.printf(
"Name: %s: %s\n",
mpBean.getName(), mpBean.getUsage()
);
}
}
Output Example:
输出示例:
Name: Eden Space: init = 6619136(6464K) used = 3754304(3666K) committed = 6619136(6464K) max = 186253312(181888K)
Name: Survivor Space: init = 786432(768K) used = 0(0K) committed = 786432(768K) max = 23265280(22720K)
Name: Tenured Gen: init = 16449536(16064K) used = 0(0K) committed = 16449536(16064K) max = 465567744(454656K)
If your have question about "Eden Space" or "Survivor Space", check out How is the java memory pool divided
如果您对“Eden Space”或“Survivor Space”有疑问,请查看java内存池是如何划分的