"Deep understanding of the JVM": OutOfMemoryError Exception Summary __JVM

Source: Internet
Author: User
Tags time zones static class throwable

In the JVM memory area, the OutOfMemoryError (OOM) exception may occur in several other run-time zones in addition to the program counters. This article sums up the oom exception, verifies the contents of the runtime zone as described in the JVM specification by code, and understands the code that might cause these areas to oom exceptions, and can locate the memory area in the work based on the exception code.

Based on the Sun's hotspot virtual machine, virtual machine startup parameters can be set in run/arguments in Eclipse, which has a direct impact on the experimental results and cannot be ignored. java Heap Overflow

The Java heap is used to store object instances, as long as the objects are created continuously and the GC roots to the object with a accessible path to prevent the garbage collection mechanism from clearing these objects and the number of objects reaching the maximum heap capacity limit, an overflow occurs.

Limit the size of the Java heap to 20MB, with the same minimum and maximum (not extensible). Dumps the current memory heap dump snapshot for subsequent analysis when a memory overflow exception occurs on the virtual machine.

Package com.jvm.OutOfMemoryError;

Import java.util.List;
Import java.util.ArrayList;

/**
 * java heap overflow
 * VM args:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror/public

class Heapoom {

    public static void Main (string[] args) {
        list<oomobject> List = new arraylist<oomobject> ();
        while (true) {
            //list reserved reference to avoid full GC recycle 
            list.add (New Oomobject ());
        }

    Static class Oomobject {

    }
}

Run Result:

Java.lang.OutOfMemoryError:Java Heap Space
dumping heap to java_pid7768.hprof ...
Heap dump file created [27987840 bytes in 0.142 secs]

This anomaly is common, typically through a memory image analysis tool, such as Eclipse Memory Analyzer, to analyze the dump dump snapshot, which is really a memory leak or a memory overflow. Memory leaks
View the leaked object to the GC roots reference chain to locate the leaked code location. Memory overflow
If there is no leakage, that is, the objects in memory must still be alive, check the JVM heap parameters (-xmx and-XMS), adjust the parameters, check the code for the existence of some objects life cycle is too long, hold the state too long, reduce the memory consumption of the program run period. virtual machine stack and local method stack Overflow

Hotspot does not differentiate between the virtual machine stack and the local method stack, the stack capacity can only be set by the-XSS parameter. StackOverflow: Thread request stack depth exceeds maximum allowed depth OutOfMemoryError: Unable to request sufficient memory space for virtual machine expansion

StackOverflow: Recursive invocation method, define a large number of local variables, increase the length of the local variable table in this method frame.

Package com.jvm.OutOfMemoryError;
/**
 * Virtual machine stack and local method stack Overflow stackoverflow
 * VM args:-xss128k/public

class Javavmstacksof {

    private int Stacklength = 1;

    Recursive calling method, defining a large number of local variables, increasing the length of the local variable table in this method frame public
    void Stackleak () {
        stacklength++;
        Stackleak ();
    }

    public static void Main (string[] args) {
        javavmstacksof oom = new Javavmstacksof ();
        try {
            oom.stackleak ();
        } catch (Throwable e) {
            System.out.println ("Stack length:" + oom.stacklength); C17/>throw e;
        }}}


Run Result:

Stack length:999
Exception in thread ' main ' Java.lang.StackOverflowError
    at Com.jvm.OutOfMemoryError.JavaVMStackSOF.stackLeak (javavmstacksof.java:26) at
    Com.jvm.OutOfMemoryError.JavaVMStackSOF.stackLeak (javavmstacksof.java:26) at
    Com.jvm.OutOfMemoryError.JavaVMStackSOF.stackLeak (javavmstacksof.java:26) ...
    

OutOfMemoryError: Multi-threaded memory overflow, and stack space is large enough there is no connection. The larger the amount of memory allocated for each thread's stack (parameter-XSS), the fewer threads can be established, the easier it will be to run out of memory when the thread is established, and the more easily the memory overflows. In this case, if you cannot reduce the number of threads or replace 64-bit virtual machines, reduce the maximum heap size and reduce the stack capacity to swap more threads.

Note : In a Windows platform virtual machine, Java threads are mapped to the operating system's kernel thread, and the following code execution can cause the system to suspend animation.

Package com.jvm.OutOfMemoryError;
/**
 * Virtual machine stack and local method stack Overflow
 * 
 *!!!!! NOTE!!!!!
 * Running the code may cause the system to suspend animation ....
 * 
 VM args:-xss2m (can be appropriately larger)/public

class Javavmstackoom {

    private void dontstop ()
        (true) {

        }
    }

    //multithreading causes stack memory overflow outofmemoryerror public
    void Stackleakbythread () {while
        (true) {
            thread thread = new Thread (new Runnable () {
                @Override public
                void Run () {
                    dontstop ();
                }
            }) ;
            Thread.Start ();
        }

    public static void Main (string[] args) {
        javavmstackoom oom = new Javavmstackoom ();
        Oom.stackleakbythread ();
    }

method area and run constant pool overflow run a constant-amount pool

JDK1.7 begins to "go permanently", and the following discussion can test the actual impact.

String.intern () is a native method that returns a reference to the string in a constant pool if the run-time pool already contains a string that is equal to the content of this string object, and if not, creates a string in the constant pool that is the same as the string content and returns a reference to the string created in the constant pool. The implementation of the Intern () method of the JDK7 differs, and when the string is not in a constant pool, it is no longer created in the constant pool the same string as this string, but instead in the constant pool, the first occurrence of the string in the heap is recorded, and the reference is returned.

Before JDK1.6, a constant pool is assigned to a permanent generation, and the following code runs under JDK1.6 to a memory overflow, which is a dead loop if it runs in the JDK1.7 and later versions:

Package com.jvm.OutOfMemoryError;

Import java.util.ArrayList;
Import java.util.List;

/**
 * Run frequent pool overflow
 * 
 * jdk1.7 and its later version has been "to the permanent generation", jdk1.6 before the operation will overflow
 *-xx:permsize=10m-xx:maxpermsize= 10M (indirectly specifying constant pool capacity size)
 */Public

class Runtimeconstantpooloom {public
    static void Main (string[] args) {
        list<string> list = new arraylist<string> ();
        int i = 0;
        while (true) {
            //list reserved reference to avoid full GC recycle 
            list.add (string.valueof (i++). Intern ());

Run Result:

Exception in thread "main" java.lang.OutOfMemoryError:PermGen spaces at
    Java.lang.String.intern (Native method)
    ......
Method Area

The method area is used to store information about the class, and if the runtime produces a large number of classes to fill the method area, a memory overflow of the method area may occur. For example, the mainstream framework spring, hibernate to a large number of classes to enhance, the use of cglib bytecode generation of dynamic classes; a large number of JSP or dynamic JSP (JSP first run needs to be compiled into Java classes).

The following is a method-area overflow caused by Cglib dynamically generated classes:

Package com.jvm.OutOfMemoryError;

Import Java.lang.reflect.Method;
Import Com.jvm.OutOfMemoryError.HeapOOM.OOMObject;

Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;
Import Net.sf.cglib.proxy.MethodProxy;

/**
 * Method Area Overflow
 *-xx:permsize=10m-xx:maxpermsize=10m/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 M, Object[] Objs, Methodproxy proxy) throws Throwable {
                    //TODO auto-generated method stub return
                    Proxy.invokesupe R (obj, OBJS);
                }
            });
            Enhancer.create ();}}

Run Result:

caused By:java.lang.OutOfMemoryError:PermGen space in
    Java.lang.ClassLoader.defineClass1 (Native method)
    ......
Local Direct Memory overflow

The Java Virtual machine can set the native direct memory available size through parameter-xx:maxdirectmemorysize, and if not specified, the default is the same size as the Java heap memory. The JDK can get the unsafe class by reflection (the unsafe Getunsafe () method only starts the class loader bootstrap to return the instance) to directly manipulate native direct memory. By using-xx:maxdirectmemorysize=10m, limit the maximum available native direct memory size of 10MB.

Import Java.lang.reflect.Field;

public class Directmemoryoom {

    private static final int _1MB = 1024 * 1024 * 1024;

    public static void Main (string[] args) throws Exception {
        Field Unsafefield = Unsafe. Class. Getdeclaredfields () [0];< C8/>unsafefield.setaccessible (true);
        Unsafe Unsafe = (Unsafe) unsafefield.get (null);

        while (true) {
            //unsafe directly wants the operating system to request memory
            Unsafe.allocatememory (_1MB);
        }
}}

Run Result:

Exception in thread ' main ' java.lang.OutOfMemoryError at
    sun.misc.Unsafe.allocateMemory (Native method)
    ......

The obvious characteristic of this anomaly is that there is no obvious exception in the heap dump file. If the file dump after Oom is relatively small, the program directly or indirectly used the Io/nio, you can consider whether this is the reason.

Reference
1, Zhou Zhiming, in-depth understanding of Java Virtual machines: JVM advanced features and best practices, machinery Industry publishing house

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.