[英]Why does the JVM have more free memory after my test program?
我做了一个测试程序来测试 Runtime.freeMemory() 方法。
public class RuntimeFreeMemory {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.freeMemory()); // 246939608
String[] arr = new String[10000000];
for (int i = 0; i < 10000000; i++)
arr[i] = new String();
System.out.println(r.freeMemory()); // 517655928
}
}
当然,这些都是很大的数字,但我真的很想测试它,因为像 10000 这样的数字不会削减它。 但是当我运行它时,我得到了一些意想不到的数字。 I thought the end free memory would go down or stay somewhat the same as the initial free memory, but instead they went over double what the initial free memory was. 我多次运行它,它总是围绕这些值。 有人可以解释一下吗?
报告的freeMemory
可能会受到 GC 以及由于您的数组分配而导致堆已扩展的事实的影响。 在开头和结尾打印r.totalMemory
并进行比较可能会很有趣。
当 JVM 启动时,它实际上并没有预先分配(默认情况下)整个堆 memory - 它只是“保留”,然后在需要时“提交”(此时,堆被扩展)。
您可以尝试将-Xms
和-Xmx
显式设置为相同的值,并且可能会获得更多预期的结果。
例如,通过使用-Xms8g -Xmx8g
我得到以下信息:
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.freeMemory()); // 8581851136
System.out.println(r.totalMemory()); // 8589934592
System.out.println("Process PID: " + ProcessHandle.current().pid());
String[] arr = new String[100000000];
for (int i = 0; i < 100000000; i++)
arr[i] = new String();
System.out.println(r.freeMemory()); // 5717141504
System.out.println(r.totalMemory()); // 8589934592
}
// compare results when using ONLY -Xmx8g
// 537178112
// 541065216
// 3240407040
// 6104809472
Note: Using -Xms
still doesn't (usually) mean that the memory is resident in RAM: Java heap Xms and linux free memory different
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.