java常见内存溢出情形

时间:2022-08-31 20:55:09
虚拟机栈溢出(如果虚拟机在扩展时无法申请到足够的内存空间将抛出OutOfMemoryError)
package com.jvm.memory;

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

public class HeapOOM {

	/**
	 * VM 运行时参数 -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
	 * @param args
	 */
	public static void main(String[] args) {
		List<OOMObject> list = new ArrayList<OOMObject>();
		while(true){
			list.add(new OOMObject());
		}
	}
	
	static class OOMObject{
		
	}
}

java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid2076.hprof ...
Exception in thread "main" Heap dump file created [24777740 bytes in 1.181 secs]
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at com.jvm.memory.HeapOOM.main(HeapOOM.java:14)
java堆用于存储对象实例,我们只要不断的创建对象,达到最大容量限制后,最后就会导致堆内存溢出,
我们如果在系统中出现这种情况就要利用映像分析工具以及对dump转储出来的快照进行分析,看创建这些类是否是有

必须要的。从2个方面检查1:看看对参数是不是设置有问题,是否还可以调大。2:检查是不是某些对象的生命周期过长。



本地方法栈溢出(如果线程请求的栈深度大于虚拟机本身所允许的最大深度,将抛出*Error)

package com.jvm.memory;

public class JavaJVMStackOOM {
	/**
	 * VM args -Xss128k
	 * @param args
	 */
	public static void main(String[] args) {
		JavaJVMStackOOM oom = new JavaJVMStackOOM();
		oom.stackLeak();
	}
	
	private int stackLenth=1;
	
	public void stackLeak(){
		stackLenth++;
		stackLeak();
	}
}

Exception in thread "main" java.lang.*Error
at com.jvm.memory.JavaJVMStackOOM.stackLeak(JavaJVMStackOOM.java:16)
at com.jvm.memory.JavaJVMStackOOM.stackLeak(JavaJVMStackOOM.java:17)


常量池溢出

package com.jvm.memory;

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

public class RuntimeConstantPoolOOM {
	/**
	 * VM Args -XX:PermSize=10 -XX:MaxPermSize=10
	 * @param args
	 */
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		int i=0;
		while(true){
			list.add(String.valueOf(i++).intern());
		}
	}
}

Error occurred during initialization of VM
Too small initial permanent heap