【发布时间】:2021-09-20 16:41:33
【问题描述】:
使用 1 GB Java 堆 (-Xmx1g),我将数据存储在许多大字节数组中。我收到OutOfMemoryError 很长一段时间之前 1 GB 的数据被存储。那时,Runtimert.maxMemory() - rt.totalMemory() + rt.freeMemory()计算的空闲堆还是蛮多的:
| byte array size | approx. data that can be stored | approx. free heap shown |
|---|---|---|
| 2^18 (262144) | 800 MB | 270 MB |
| 2^17 (131072) | 930 MB | 140 MB |
| 2^16 (65536) | 997 MB | 72 MB |
| 2^15 (32768) | 1032 MB | 36 MB |
为什么大字节数组的堆大小计算被关闭,我可以做些什么来修复它?
注意:当使用 2^19(或更大)大小的字节数组时,会发生不同的情况:Java byte array of 1 MB or more takes up twice the RAM - 让我们将这个问题集中在 2^18 大小的字节数组上。
在 Windows java -cp .\lib\* -Xmx1g tryit.Main 和 Debian java -cp .:./lib/* -Xmx1g tryit.Main 上使用 64 位服务器 VM AdoptOpenJDK 11.0.11 运行:
package tryit;
public class Main {
public static void main(String[] args) throws Exception {
byte[][] array = new byte[1000000][];
long freeAtStart = free();
System.out.println("Free at start: " + freeAtStart);
int chunkSize = 2<<17; // This is 2^18.
System.out.println("Chunk size : " + chunkSize);
for (int n = 0; n < 1000000; n++) {
if (n % 50 == 0) {
long currentFree = free();
System.out.printf("%d: stored %d / allocated %d / free %d\n", n, n * chunkSize, freeAtStart - currentFree, currentFree);
}
array[n] = new byte[chunkSize];
}
}
static long free() throws Exception {
System.gc(); // Called just in case - there should not be anything to garbage collect.
Thread.sleep(100); // Give GC some time to work
return Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory();
}
}
最后是四次运行的(缩短的)输出:
2^15:
Free at start: 1068751960 / Chunk size: 32768
31500: stored 1032192000 / allocated 1032933912 / free 35818048
2^16:
Free at start: 1068751960 / Chunk size: 65536
15200: stored 996147200 / allocated 996627400 / free 72124560
2^17:
Free at start: 1068751960 / Chunk size: 131072
7100: stored 930611200 / allocated 930960032 / free 137791928
2^18:
Free at start: 1068751960 / Chunk size: 262144
3050: stored 799539200 / allocated 799823160 / free 268928800
2^19 (humongous objects - allocation size is two times stored size):
Free at start: 1068751960 / Chunk size: 524288
1000: stored 524288000 / allocated 1048811120 / free 19940840
【问题讨论】:
-
您的测试不正确。
System.gc();将不会以 100% 启动 GC。这是对 JVM 这样做的唯一建议。 JVM 可以不做 GC。 -
我打电话给
System.gc()“以防万一”。没有垃圾回收的东西(一切都是强引用的),所以例子不需要尝试触发gc。 -
这是我在 Java 17 上 2^18 的输出:
3050: stored 799539200 / allocated 1064828992 / free 1617856edit 删除了gc()调用,我得到了267966664,即和你很相似。所以 gc 调用确实有所作为? -
1GB不仅仅由你使用 - VM 也有它的数据,而且它甚至没有完全提供给你,垃圾收集器需要他们自己的结构才能工作,比如 SATB 队列,甚至 @ 987654323@。你看到的对我来说很正常。 -
@oleg.cherednik 在当前实现下,我检查了一些,它会(假设默认标志)。问题是
System.gc启动了一个并发标记阶段——触发(或不触发)的内容取决于当前堆。
标签: java arrays memory out-of-memory