Here are several typical memory overflow cases in Java!

Keywords: Java JDK jvm Programming

Here are several typical memory overflow cases in Java!

Write in front
As a programmer, more or less will encounter some memory overflow scenarios. If you haven't yet, it means that you may have a relatively short working life, or you are a fake programmer at all! Ha ha, make a joke. Today, we will list several typical memory overflow cases in the way of Java code. I hope you can avoid writing these low level codes in your daily work.

Define main class structure
First, we create a class named BlowUpJVM, and then all the case experiments are based on this class. As shown below.

public class BlowUpJVM {
}
Stack depth overflow
public static void testStackOverFlow(){

  BlowUpJVM.testStackOverFlow(); 

}
Stack recursion, and no processing, so the virtual machine stack is constantly in-depth, so the stack depth overflows.

Permanent generation memory overflow
public static void testPergemOutOfMemory1(){
//Method 1 failed
List list = new ArrayList();
while(true){

  list.add(UUID.randomUUID().toString().intern()); 

}
}
I plan to pile up the String constant pool, but it failed. After JDK 1.7, the constant pool is put in the heap, and garbage collection can also be carried out.

Then use cglib and Class to fill up the elderly

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

}
}
The virtual machine successfully overflowed the memory. Can the classes generated by the JDK dynamic agent overflow?

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

}
}
The fact shows that the bad classes of JDK dynamic agent will not cause memory overflow, because: the class information generated by JDK dynamic agent will not be put in the permanent generation, but in the heap.

Local method stack overflow
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() { 
        } 
     }); 
  } 

}
}
This principle is to create thread pools continuously, and each thread pool creates 10 threads. These thread pools are in the local method area, and over time, the local method area overflows.

JVM stack memory overflow
public static void testStackOutOfMemory(){

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

}
The creation of threads will be directly created in the JVM stack, but in this example, no memory overflow is seen. The host hangs first, not the JVM, but really the host, whether in mac or windows.

Warm reminder, this will really crash.

Heap overflow
public static void testOutOfHeapMemory(){
List list = new ArrayList();
while(true){

  StringBuffer B = new StringBuffer(); 
  for(int i = 0 ; i < 10000 ; i++){ 
     B.append(i); 
  } 
  list.add(B); 

}
}
Keep adding StringBuffer objects to the heap, and it will overflow when the heap is full.

Test case full code
public class BlowUpJVM {

//Stack depth overflow
public static void  testStackOverFlow(){ 
      BlowUpJVM.testStackOverFlow(); 
} 

//Cannot cause permanent generation overflow
public static void testPergemOutOfMemory1(){ 
   //Method 1 failed 
    List<String> list = new ArrayList<String>(); 
   while(true){ 
      list.add(UUID.randomUUID().toString().intern()); 
   } 
} 

//Permanent generation overflow
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(); 
   } 
} 

//No permanent generation overflow
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; 
         } 
      }); 
   } 
} 

//Local method stack overflow
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 memory overflow
public static void testStackOutOfMemory(){ 
    while (true) {   
            Thread thread = new Thread(new Runnable() {   
                   public void run() { 
                          while(true){ 
                      } 
                   }   
            });   
            thread.start();   
     }   
} 

//Heap overflow
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); 
   } 
} 

}
Write at the end
If you think the article is of some help to you, please search and pay attention to the ice technology WeChat official account by WeChat, and learn the concurrent programming technology with glacier.

Finally, I attach the core skills and knowledge map that we need to master in concurrent programming. I wish you to avoid detours in learning concurrent programming.

Original address https://www.cnblogs.com/binghe001/p/12952772.html

Posted by pomme on Sun, 24 May 2020 19:43:06 -0700