JVM常见内存溢出问题归纳

OutOfMemoryError发生有三种比较常见的情况:

  1. 堆溢出,简单说就是创建了太多的实例对象,导致内存溢出
    • OutOfMemoryError
  2. 栈溢出, 栈的深度不够或者多线程导致栈内存不足,导致内存溢出
    • StackOverFlowError
    • OutOFMemoryError
  3. 方法区溢出, 方法区用于存放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”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值