源代码:MyTes1.java
public class MyTest2 {
public static void main(String[] args) {
List<MyTest1> list = new ArrayList<>();
for (; ; ) {
list.add(new MyTest1());//为什么不直接new MyTest1();
}
}
}
调整VMOption参数:
-Xms5m -Xmx5m -XX:+HeapDumpOnOutOfMemoryError(其中这个参数是将内存溢出的错误以转储文件的形式体现在磁盘上)
执行结果:
java.lang.OutOfMemoryError: GC overhead limit exceeded
Dumping heap to java_pid18364.hprof ...
Heap dump file created [8939566 bytes in 0.043 secs]
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.compass.spring_lecture.memory.MyTest2.main(MyTest2.java:16)
image.png
对于堆转储文件的分析,使用jvisualvm(对多种工具的整合)进行分析:
C:\Users\Administrator>jvisualvm
C:\Users\Administrator>
The launcher has determined that the parent process has a console and will reuse it for its own console output.
Closing the console will result in termination of the running program.
Use '--console suppress' to suppress console output.
Use '--console new' to create a separate console window.
打开VisualVM:
image.png image.png
image.png
image.png
看一看错误的声明:
java.lang public class OutOfMemoryError
extends VirtualMachineError
因为内存的溢出,导致JVM不能分配一个对象的时候抛出,没有更多的内存可以被垃圾回收器获取,虚拟机可以构造OutOfMemoryError对象,就好像禁用了压制和/或堆栈跟踪不可写一样。
Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
Since:
JDK1.0
public class MyTest2 {
public static void main(String[] args) {
List<MyTest1> list = new ArrayList<>();
for (; ; ) {
list.add(new MyTest1());//为什么不直接new MyTest1();
System.gc(); //显示的调用GC来进行垃圾回收
}
}
}
image.png
网友评论