Java Virtual Machine (1) Automatic Memory Management Mechanism

Source: Internet
Author: User

Java Virtual Machine (1) Automatic Memory Management Mechanism
Java memory overflow exceptionI. Summary

We can learn with the following questions:Automatic Memory Management Mechanism, As shown below:

What operations may cause memory overflow? What types of memory overflow are there? Which areas of memory are full? What are the principles of garbage collection? What garbage collection algorithms and their implementation are available? What are the recovery strategies of the New Generation and old generation? What do memory-related JVM parameters mean?

This article mainly summarizes question 1, question 2 and question 3

2. Data Area During Running

During Java program execution, the Java Virtual Machine divides the memory it manages into several different data regions, as shown in


 

The Virtual Machine stack, local method stack, and program technician are private threads, and the method zone and heap are shared by threads.

 

2.1 program counter

Role: row number indicator of the bytecode executed by the current thread

 

When the bytecode interpreter is working, it changes its value to select the next bytecode instruction branch, loop, jump, exception handling, and thread recovery to be executed. 2.2 Virtual Machine Stack

Stack function: Stack is used to store information such as local variable table, operand stack, dynamic link, and method exit.

The local variable table is used to store eight basic data types (boolean, byte, char, short, int, float, long, double) and reference.

Reference Type:

Reference pointer pointing to the starting address of the object

Pointing to a handle representing the object

Address pointing to a bytecode instruction

Two exception conditions can be thrown.

The stack depth requested by the thread is greater than the stack depth allowed by the virtual machine, and an StackOverflowError error is thrown.

An OutOfMemoryError error is thrown when the extended memory cannot be applied.

2.3 local method Stack

The role of the VM stack is very similar to that of the VM stack. The difference is thatThe Virtual Machine stack executes the Java method service, while the local method stack serves the Native method used by the virtual machine.

StackOverflowError and OutOfMemoryError exceptions are also thrown.

2.4 heap

Heap: allocates all object instances and arrays. You can throw an OutOfMemoryError.

2.5 method Zone

Function of the Method Area: used to store Class information, constants (final modifier), static variables (static), and code Compiled by the real-time compiler loaded by virtual machines)

You can throw an OutOfMemoryError.

2.6 running frequent volume pool

It is part of the method area and is used to store various literal quantities and symbolic references generated during the compilation period (This will be discussed later ), after the class is loaded, it is stored in the runtime pool of the method area. You can throw an OutOfMemoryError.

III, Object Access

Two mainstream access methods: Use a handle and a direct pointer. (A HotSpot VM is accessed using a direct pointer)

Access using a handle


Direct pointer access


Comparison of advantages and disadvantages

 

IV, OutOfMemoryError exception

In the Java Virtual Machine Specification Description, in addition to program counters, The OutOfMemoryError may occur in several other runtime Time Zone regions of the virtual machine memory.

The following examples are used to verify the exceptions.Note the Virtual Machine startup parameters that need to be set during execution at the beginning of the following code. These parameters have a direct impact on the experiment results. Do not ignore them when debugging the code.

4.1Java Heap Overflow

The new object is put in the heap, so this part is simple and new objects can be updated constantly, but to prevent the object from being GC after it is new, so put the new object in a List. For better results, you can adjust the heap parameters before running.

import java.util.ArrayList;import java.util.List;/** * VM Args: -Xms20m -Xms20m - XX:+HeapDumpOnOutOfMemoryError * @author Administrator * */public class HeapOOM {       static class OOMObject{}       public static void main(String[] args) {            List
 
   list = new ArrayList
  
   ();             while(true ){                  list.add( new OOMObject());            }      }}
  
 


Running result

Java. lang. OutOfMemoryError: Java heap space Dumping heap to java_pid1_8.hprof... Heap dump file created [364376345 bytes in 15.891 secs] 4.2 VM Stack OverflowIn the heap of a single thread, we constantly increase the number of member variables. The unit containing this variable cannot bear this variable, and StackOverflowError is thrown. If you can open as many threads as possible and call the native method in each thread, an OutOfMemoryError will be thrown.
/** * VM Args: - Xss64k * @author Administrator * */public class JavaVMStackSOF {       private int stackLength = 1;       public void stackLeak(){             stackLength ++;            stackLeak();      }       public static void main(String[] args) throws Throwable {            JavaVMStackSOF oom = new JavaVMStackSOF();             try{                  oom.stackLeak();            } catch(Throwable e){                  System. out.println(Stack length: + oom.stackLength);                   throw e;            }      }}


Running result
Stack length:914        Exception in thread main java.lang.StackOverflowError              at JavaVMStackSOF.stackLeak(                   JavaVMStackSOF.java:9         )              at JavaVMStackSOF.stackLeak(                   JavaVMStackSOF.java:10         )              at JavaVMStackSOF.stackLeak(                   JavaVMStackSOF.java:10         )        



4.3 method OverflowYou can use an enhanced Class loading method. The basic idea is that a large number of classes are generated during the runtime to fill the method area until the overflow occurs. The third-party class library CGLib is used to directly operate on bytecode to generate a large number of dynamic classes.
import java.lang.reflect.Method;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodProxy;/** * VM Args:- XX:PermSize=10m -XX:MaxPermSize=10m * @author Administrator * */public class JavaMethodAreaOOM {       public static void main(String[] args) {             while (true ){                  Enhancer enhancer = new Enhancer();                  enhancer.setSuperclass(OOMObject. class );                  enhancer.setUseCache( false );                  enhancer.setCallback( new MethodInterceptor() {                         @Override                         public Object intercept(Object obj, Method method, Object[] args,                                    MethodProxy proxy) throws Throwable {                               return proxy.invoke(obj, args);                        }                  });                  enhancer.create();            }      }       static class OOMObject{                   }}


Running result java. lang. outOfMemoryError: PermGen space at java. lang. classLoader. defineClass1 (Native Method) at java. lang. classLoader. defineClassCond (ClassLoader. java: 631) at java. lang. classLoader. defineClass (ClassLoader. java: 615 )... 8 more 4.4 running frequent volume pool overflowThe intern method of the String class can be used.
import java.util.ArrayList;import java.util.List;/** * VM Args:- XX:PermSize=10m -XX:MaxPermSize=10m * @author Administrator * */public class RuntimeConstantPoolOOM {       public static void main(String[] args) {            List
 
   list = new ArrayList
  
   ();             int i = 0;             while (true ){                  list.add(String. valueOf(i++).intern());            }      }}
  
 


Running result Exception in thread main java. lang. OutOfMemoryError: PermGen space at java. lang. String. intern ( Native Method) At RuntimeConstantPoolOOM. main ( RuntimeConstantPoolOOM. java: 14) V. Summary

This section describes how the memory in the virtual machine is divided, what areas, what code and operations may cause memory overflow exceptions.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.