几种典型的内存溢出案例

今天,我们就以Java代码的方式来列举几个典型的内存溢出案例,希望大家在日常工作中,尽量避免写这些low水平的代码。

定义主类结构

首先,我们创建一个名称为BlowUpJVM的类,之后所有的案例实验都是基于这个类进行。如下所示。

public class BlowUpJVM {  
}

第一种:栈深度溢出

public static void  testStackOverFlow(){ 
      BlowUpJVM.testStackOverFlow(); 
} 

栈不断递归,而且没有处理,所以虚拟机栈就不断深入不断深入,栈深度就这样溢出了。

第二种:永久代内存溢出

public static void testPergemOutOfMemory1(){ 
   //方法一失败 
   List<String> list = new ArrayList<String>(); 
   while(true){ 
      list.add(UUID.randomUUID().toString().intern()); 
   } 
} 

打算把String常量池堆满,没想到失败了,JDK1.7后常量池放到了堆里,也能进行垃圾回收了。

然后换种方式,使用cglib,用Class把老年代取堆满

public static void testPergemOutOfMemory2(){ 
   try { 
      while (true) { 
         Enhancer enhancer = new Enhancer(); 
         enhancer.setSuperclass(OOM.class); 
         enhancer.setUseCache(false); 
         enhancer.setCallback(new MethodInterceptor() { 
            @Override 
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 
               return proxy.invokeSuper(obj, args); 
            } 
         }); 
         enhancer.create(); 
      } 
   } 
   catch (Exception e){ 
      e.printStackTrace(); 
   } 
} 

虚拟机成功内存溢出了,那JDK动态代理产生的类能不能溢出呢?

public static void testPergemOutOfMemory3(){ 
   while(true){ 
   final OOM oom = new OOM(); 
   Proxy.newProxyInstance(oom.getClass().getClassLoader(), oom.getClass().getInterfaces(), new InvocationHandler() { 
         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
            Object result = method.invoke(oom, args); 
            return result; 
         } 
      }); 
   } 
} 

事实表明,JDK动态代理差生的类不会造成内存溢出,原因是:JDK动态代理产生的类信息,不会放到永久代中,而是放在堆中。

第三种:本地方法栈溢出

public static void testNativeMethodOutOfMemory(){ 
   int j = 0; 
   while(true){ 
      Printer.println(j++); 
      ExecutorService executors = Executors.newFixedThreadPool(50); 
      int i=0; 
      while(i++<10){ 
         executors.submit(new Runnable() { 
            public void run() { 
            } 
         }); 
      } 
   } 
} 

这个的原理就是不断创建线程池,而每个线程池都创建10个线程,这些线程池都是在本地方法区的,久而久之,本地方法区就溢出了。

第四种:JVM栈内存溢出

public static void testStackOutOfMemory(){ 
    while (true) {   
            Thread thread = new Thread(new Runnable() {   
                   public void run() { 
                          while(true){ 
                      } 
                   }   
            });   
            thread.start();   
     }   
} 

线程的创建会直接在JVM栈中创建,但是本例子中,没看到内存溢出,主机先挂了,不是JVM挂了,真的是主机挂了,无论在mac还是在windows,都挂了。

注意:这个是真的会死机的。

第五种:堆溢出

public static void testOutOfHeapMemory(){ 
   List<StringBuffer> list = new ArrayList<StringBuffer>(); 
   while(true){ 
      StringBuffer B = new StringBuffer(); 
      for(int i = 0 ; i < 10000 ; i++){ 
         B.append(i); 
      } 
      list.add(B); 
   } 
} 

不断往堆中塞新增的StringBuffer对象,堆满了就直接溢出了。

测试案例完整代码

下面是以上五种案例的完整代码:

public class BlowUpJVM {
    //栈深度溢出
    public static void  testStackOverFlow(){ 
          BlowUpJVM.testStackOverFlow(); 
    } 

    //不会引起永久代溢出
    public static void testPergemOutOfMemory1(){ 
       //方法一失败 
        List<String> list = new ArrayList<String>(); 
       while(true){ 
          list.add(UUID.randomUUID().toString().intern()); 
       } 
    } 

    //永久代溢出
    public static void testPergemOutOfMemory2(){ 
       try { 
          while (true) { 
             Enhancer enhancer = new Enhancer(); 
             enhancer.setSuperclass(OOM.class); 
             enhancer.setUseCache(false); 
             enhancer.setCallback(new MethodInterceptor() { 
                @Override 
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 
                   return proxy.invokeSuper(obj, args); 
                } 
             }); 
             enhancer.create(); 
          } 
       } 
       catch (Exception e){ 
          e.printStackTrace(); 
       } 
    } 

    //不会引起永久代溢出
    public static void testPergemOutOfMemory3(){ 
       while(true){ 
       final OOM oom = new OOM(); 
       Proxy.newProxyInstance(oom.getClass().getClassLoader(), oom.getClass().getInterfaces(), new InvocationHandler() { 
             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
                Object result = method.invoke(oom, args); 
                return result; 
             } 
          }); 
       } 
    } 

    //本地方法栈溢出
    public static void testNativeMethodOutOfMemory(){ 
       int j = 0; 
       while(true){ 
          Printer.println(j++); 
          ExecutorService executors = Executors.newFixedThreadPool(50); 
          int i=0; 
          while(i++<10){ 
             executors.submit(new Runnable() { 
                public void run() { 
                } 
             }); 
          } 
       } 
    } 

    //JVM内存溢出
    public static void testStackOutOfMemory(){ 
        while (true) {   
                Thread thread = new Thread(new Runnable() {   
                       public void run() { 
                              while(true){ 
                          } 
                       }   
                });   
                thread.start();   
         }   
    } 

    //堆溢出
    public static void testOutOfHeapMemory(){ 
       List<StringBuffer> list = new ArrayList<StringBuffer>(); 
       while(true){ 
          StringBuffer B = new StringBuffer(); 
          for(int i = 0 ; i < 10000 ; i++){ 
             B.append(i); 
          } 
          list.add(B); 
       } 
    } 
}

建议:希望动动你的手,找机会把上面代码都运行一遍,你会得到不一样的收获。

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tzk_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值