public class Test {
        public static void main(String[] args) {
            long heapsize = Runtime.getRuntime().totalMemory();
            System.out.println("heapsize is :: " + heapsize/(1024*1024));
        }

}

输出为:

堆大小为:: 245

这是否意味着我的运行时只有245M内存?我的电脑有8GB内存。我怀疑输出是否正确,因为仅运行Eclipse会消耗超过245M的内存。

在Eclipse中,单击Windows-> Preferences-> Java-> Installed JRE,然后按如下所示设置Default JVM参数:
-ea -Xms256m -Xmx4096M

然后再次运行测试。它仍然打印出相同的数字245。这怎么可能?

编辑:从Java文档中获取Runtime.getRuntime()。totalMemory():
Returns the total amount of memory in the Java virtual machine.
The value returned by this method may vary over time, depending on the
host environment.

最佳答案

您的程序不在Eclipse的堆空间中运行。 Eclipse为您的程序生成了一个单独的JVM。
Runtime.totalMemory()确实返回当前堆大小。
-Xms参数指定初始堆大小。如果Java无法通过垃圾回收释放足够的内存,直到达到-Xmx设置的最大值,Java就会扩展。此时,JVM将以OutOfMemoryError退出。

Java内存管理是一个复杂的主题,涉及垃圾收集,将对象从托儿所移至保管空间等。

关于java - 在Eclipse中设置的运行时堆大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35978477/

10-14 19:38
查看更多