gpt4 book ai didi

java - -Xmx 是硬性限制吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:51 25 4
gpt4 key购买 nike

SO answer澄清了一些关于 -Xmx JVM 标志的事情。为了进行实验,我做了以下事情:

import java.util.List;
import java.util.ArrayList;

public class FooMain {

private static String memoryMsg() {
return String.format("%s. %s. %s"
, String.format("total memory is: [%d]",Runtime.getRuntime().totalMemory())
, String.format("free memory is: [%d]",Runtime.getRuntime().freeMemory())
, String.format("max memory is: [%d]",Runtime.getRuntime().maxMemory()));
}

public static void main(String args[]) {
String msg = null;
try {
System.out.println(memoryMsg());
List<Object> xs = new ArrayList<>();
int i = 0 ;
while (true) {
xs.add(new byte[1000]);
msg = String.format("%d 1k arrays added.\n%s.\n"
, ++i
, memoryMsg());
}
} finally {
System.out.printf(msg);
}
}
}

javac FooMain.java编译它。当我以 500 万字节的最大堆大小运行它时,我得到:

java -Xmx5000000 FooMain
total memory is: [5242880]. free memory is: [4901096]. max memory is: [5767168]
4878 1k arrays added.
total memory is: [5767168]. free memory is: [543288]. max memory is: [5767168].
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.String.toCharArray(String.java:2748)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:3048)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2744)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2702)
at java.util.Formatter.format(Formatter.java:2488)
at java.util.Formatter.format(Formatter.java:2423)
at java.lang.String.format(String.java:2792)
at FooMain.memoryMsg(FooMain.java:7)
at FooMain.main(FooMain.java:21)

虽然数字足够接近,但它们似乎不是很准确(除了最后的total memory exactly max memory )。特别是 5368 个 1000 字节的数组,每个数组应该占用超过 5000000 甚至 5242880 字节。这些数字应该如何理解?

这是我正在使用的 java:

java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) Server VM (build 24.80-b11, mixed mode)

最佳答案

查看 OpenJDK 源代码,确定最大堆大小的逻辑非常复杂,并且由很多变量决定。实际堆大小在 hotspot/src/share/vm/memory/collectorPolicy.cpp 中设置,它使用提供的 -Xmx 值作为输入,并使用以下代码将其对齐:

align_size_up(MaxHeapSize, max_alignment());

align_size_up 定义为:

#define align_size_up_(size, alignment) (((size) + ((alignment) - 1)) & ~((alignment) - 1))

而max_alignment是虚拟内存页面大小和JVM垃圾收集卡大小的乘积。 VM 页面大小为 4096 字节,卡大小为 512 字节。代入这些值会得到 6324224 字节的实际 MaxHeapSize,这与您看到的数字非常吻合。

注意:我只是简单地查看了 JVM 代码,所以我可能错过了一些东西,但答案似乎与您所看到的相加。

关于java - -Xmx 是硬性限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com