最好的 Java 代码来控制使用的大堆内存(比如 1G)

best Java code to control big heap memeory used (like 1G)

目前,我需要编写一个Java程序(不关心它的功能)只是为了使用巨大的堆内存进行测试。

编写一个简短的 java 代码可以精确控制要使用多少堆,这将非常有用。

创建这样的程序非常简单,只需创建更多对象并且不要让它们进行垃圾回收。一个例子如下。

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

public class UseHugeRAM {

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    int counter = 0;
    for (;;) {
        list.add("" + counter++);
    }
  }
}

您可以很好地将循环绑定到某个值,以便它在创建这么多字符串对象后退出。现在这将简单地耗尽内存而不是终止。希望对你有帮助。

In nutshell you are storing all the objects and not letting them garbage collect. That's something you should protect while building your application.

快速分配1GB内存:

byte[][] memoryWaster = new byte[1024][1_048_576];

请参阅下面的上次测试 运行 以了解是否成功分配 16 GB 内存。

测试程序

Runtime runtime = Runtime.getRuntime();
System.out.printf("total: %11d   max: %d%n", runtime.totalMemory(), runtime.maxMemory());
System.out.printf("used:  %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc:    %11d%n", runtime.totalMemory() - runtime.freeMemory());
byte[][] memoryWaster = new byte[1024][1_048_576];
memoryWaster[0][0] = 2; // prevent unused warning
System.out.printf("new[]: %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc:    %11d%n", runtime.totalMemory() - runtime.freeMemory());
memoryWaster = null;
System.out.printf("null:  %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc:    %11d%n", runtime.totalMemory() - runtime.freeMemory());

输出(Java 8、32 位):

// Java 1.8.0_51, 32-bit, no -Xmx given
total:    16252928   max: 259522560
used:       543288
gc:         349296
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at test.Test.main(Test.java:11)

// Java 1.8.0_51, 32-bit, -Xmx1200m
total:    16252928   max: 1216348160
used:       543288
gc:         349296
new[]:  1078435312
gc:     1078382592
null:   1078382592
gc:       15711288

// Java 1.8.0_51, 64-bit, no -Xmx given, 32 GB machine
total:   514850816   max: 7618953216
used:      5389872
gc:        2981048
new[]:  1074961632
gc:     1081175720
null:   1081175720
gc:       13027424

// Java 1.8.0_51, 64-bit, -Xmx1200m
total:   514850816   max: 1118830592
used:      5389872
gc:        2981048
new[]:  1077948560
gc:     1078944096
null:   1078944096
gc:        3501136

// Java 1.8.0_51, 64-bit, -Xmx20g, new byte[16384][1_048_576]
total:   514850816   max: 19088801792
used:      5389872
gc:        2981048
new[]: 17205604928
gc:    17205604928
null:  17205604928
gc:       26186032