【Java】几种典型的内存溢出案例,都在这儿了!

写在前面

做为程序员,多多少少都会遇到一些内存溢出的场景,若是你还没遇到,说明你工做的年限可能比较短,或者你根本就是个假程序员!哈哈,开个玩笑。今天,咱们就以Java代码的方式来列举几个典型的内存溢出案例,但愿你们在平常工做中,尽可能避免写这些low水平的代码。java

定义主类结构

首先,咱们建立一个名称为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后常量池放到了堆里,也能进行垃圾回收了。windows

而后换种方式,使用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动态代理产生的类信息,不会放到永久代中,而是放在堆中。app

本地方法栈溢出

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个线程,这些线程池都是在本地方法区的,长此以往,本地方法区就溢出了。dom

JVM栈内存溢出

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

线程的建立会直接在JVM栈中建立,可是本例子中,没看到内存溢出,主机先挂了,不是JVM挂了,真的是主机挂了,不管在mac仍是在windows,都挂了。jvm

舒适提示,这个真的会死机的。ide

堆溢出

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); 
       } 
    } 
}

写在最后

若是以为文章对你有点帮助,请微信搜索并关注「 冰河技术 」微信公众号,跟冰河学习高并发编程技术。

最后,附上并发编程须要掌握的核心技能知识图,祝你们在学习并发编程时,少走弯路。

相关文章
相关标签/搜索