测试代码
class User{ }public class Program { public static void main(String[] args) { Listlist=new ArrayList<>(); while(true){ User user=new User(); list.add(user); } }}
配置JVM参数
-XX:+HeapDumpOnOutOfMemoryError -Xms20m -Xmx20m
运行报错
java.lang.OutOfMemoryError: Java heap spaceDumping heap to java_pid11944.hprof ...Heap dump file created [27895404 bytes in 0.123 secs]Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2245) at java.util.Arrays.copyOf(Arrays.java:2219) at java.util.ArrayList.grow(ArrayList.java:242) at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:216) at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:208) at java.util.ArrayList.add(ArrayList.java:440) at com.jvm.Program.main(Program.java:11)
在项目根目录下,有个快照文件,使用Eclipse Memory Analyzer打开
发现大部分内存被main线程占用了
而这些内存都用来保存User对象了