OutOfMemoryError发生有三种比较常见的情况:
- 堆溢出,简单说就是创建了太多的实例对象,导致内存溢出
- OutOfMemoryError
- 栈溢出, 栈的深度不够或者多线程导致栈内存不足,导致内存溢出
- StackOverFlowError
- OutOFMemoryError
- 方法区溢出, 方法区用于存放Class的相关信息,可能出现情况,java 反射创建了太多的类,导致内存溢出
- OutOFMemoryError
Java Heap Overflow Sample
/**
* VM Args : -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
* @author marshall
*
*/
public class HeapOOM {
static class OOMOBj{
}
public static void main(String[] args) {
List<OOMOBj> list =new ArrayList<HeapOOM.OOMOBj>();
while(true){
list.add(new OOMOBj());
}
}
}
Result:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
StackOverflow Sample
/**
* VM Args:-Xss 128k
* @author marshall
*
*/
public class VMStackSOF {
private int stackLength=1;
public void stackLeak(){
stackLength++;
stackLeak();
}
public static void main(String[] args) throws Exception {
VMStackSOF oom=null;
try {
oom=new VMStackSOF();
oom.stackLeak();
} catch (Exception e) {
System.out.println("stack length:"+oom.stackLength);
throw e;
}
}
}
Result:
Exception in thread “main” java.lang.StackOverflowError
MethodArea OutOfMemory Sample
/**
* VM Args:-XX:PermSize=5m -XX:MaxPermSize=5m
* @author marshall
*
*/
public class MethodAreaOOM {
static class OOMObject{
}
public static void main(String[] args) throws Exception {
try{
while(true){
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(OOMObject.class);
enhancer.setUseCache(false);
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
return proxy.invokeSuper(obj, args);
}
});
enhancer.create();
}}
catch(Exception e)
{
System.out.println(e.getCause());
System.out.println(e.getMessage());
throw e;
}
}
}
Result:
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread “main”