Geo*_*org 2 java memory arrays out-of-memory
我使用 1 GB Java 堆 ( -Xmx1g) 将数据存储在许多大型字节数组中。我花了OutOfMemoryError相当长的时间才存储 1 GB 的数据。此时,根据 Runtime 计算,还有相当多的空闲堆rt.maxMemory() - rt.totalMemory() + rt.freeMemory():
| 字节数组大小 | 约。可存储的数据 | 约。显示空闲堆 |
|---|---|---|
| 2^18 (262144) | 800MB | 270MB |
| 2^17 (131072) | 930MB | 140MB |
| 2^16 (65536) | 997MB | 72MB |
| 2^15 (32768) | 1032MB | 36MB |
为什么大字节数组的堆大小计算关闭,我可以做些什么来修复它吗?
注意:当使用 2^19(或更大)大小的字节数组时,会发生不同的情况:1 MB 或更多的 Java 字节数组占用两倍的 RAM - 让我们将这个问题集中在 2^18 大小的字节数组上。
java -cp .\lib\* -Xmx1g tryit.Main在 Windows和 Debian上使用 64 位服务器 VM AdoptOpenJDK 11.0.11 运行java -cp .:./lib/* -Xmx1g tryit.Main:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
最后是四次运行的(缩短的)输出:
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
Run Code Online (Sandbox Code Playgroud)
如链接答案(1 MB 或更多的 Java 字节数组占用 RAM 的两倍)和G1 垃圾收集器文档中所述,G1 垃圾收集器将堆划分为每个 1 MByte(2^20 字节)的区域。对于提供 1024 个区域的 1GB 堆(由于管理开销可能会少一些)。
天真地你会期望 2^20 字节的区域可以容纳 4 个字节数组,每个字节数组为 2^18 字节 - 但不幸的是事实并非如此。字节数组是对象,对象有一个隐藏的对象头(有关说明,请参阅/sf/answers/3535648441/ )。
所以 a 的有效大小byte[262144]不是 262144 字节,而是 262160 字节(取决于 JVM 和最大堆大小,它可能更大),这意味着每个区域只能容纳 3 个长度为 262144 的字节数组。
将每个区域 3 个字节数组与 1024 个区域组合起来,对于 1 GB 堆,最多可以得到 3072 个字节数组(262144 字节),这与您的数字非常匹配。
您可以采取什么措施:
-XX:G1HeapRegionSize=4M) - 4MB 区域可以容纳长度为 262144 的 15 个字节数组,而 4 个 1MB 区域只能容纳长度为 262144 的 12 个字节数组注意:本文使用 2^20 表示2 的 20 次方,这与 java 表达式不同2^20,而是1<<20