Simple analysis of Java OutOfMemoryError

Source: Internet
Author: User

Simple analysis of Java OutOfMemoryError

  The recent code encountered a Java memory overflow problem, so I wanted to summarize some of the chestnuts that caused the Java memory overflow, and how to solve the Java memory overflow.

Java Heap Overflow

The Java heap is used to store object instances, as long as the objects are constantly created and the GC roots to an reachable path between the objects to prevent the garbage collection mechanism from clearing these objects, then a memory overflow exception occurs after the number of objects reaches the maximum heap capacity limit.

The following is a test of the heap memory overflow exception through a piece of code.

1  Public classheapoom{2   Static classheapoom{3     }4     Public Static voidMain (string[] args)5   {6list<oomobject> list =NewArraylist<oomobject> ();7while (1)8        {9List.add (Newoomobject ());Ten     } One }       A}

  The limit size for Java heap in code is 20M and is not extensible. The specific settings are in VM Args:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror.

When there is a heap overflow exception, "Java.lang.OutOfMemoryError" appears in the exception stack Information Bar and then prompts: "Java heap Space".

  Solution Ideas:

In general, the dump dump snapshot is analyzed using the memory image analysis tool, with a focus on confirming if the object in memory is necessary, that is, whether it is a memory Leak, or OverFlow (memory overflow). In the case of a memory leak, a tool can be used to check the reference chain of the leaking object to the GC roots. The location of the leak code can then be located.

If it is not a memory leak, it means that the objects in memory are alive. Then check the parameters of the virtual machine, and compare it to the physical machine to see if it can be adjusted, from the code to check if there is an object with too long life cycle, and try to reduce the memory consumption during the program running.

Virtual machine stack and local method stack Overflow

Because the virtual machine stack and the local method stack are not distinguished in the hotspot virtual machine, the-xoss (used to set the size of the local method stack) parameter exists, but is actually invalid. Stack capacity is only set by the-XSS parameter.

Here is the test code for the virtual machine and the local method stack Oom:

1  Public classjavavmstacksof{2     Private intStacklength = 1;3      Public voidStackleak () {4stacklength++;5 stackleak ();6     }7      Public Static voidMain (string[] args) {8javavmstacksof com =Newjavavmstacksof ();9         Try{Ten com.stackleak (); One         } A         Catch(Throwable e) { -System.out.println ("Stack Length" +com.stacklength); -             Throwe; the         } -     } -}

The above code uses-xss=128k, reducing the capacity of the stack memory, the result throws Stackoverflowerror exception, the exception appears when the output of the stack depth of the corresponding reduction.

A large number of local variables are defined, increasing the length of the local variable table in this method frame, and the output stack depth shrinks as the result of throwing stackoverflowerror exceptions. That is, in a single thread, either because the stack frame is too large or the virtual machine stack capacity is too small, when the memory can not be allocated, will throw stackoverflowerror exception.

  Solution Ideas:

If you use the virtual machine default parameters, the stack depth in most cases to 1000-2000 no problem, the normal method calls (including recursion), this depth is fully sufficient, if the establishment of multithreading caused memory overflow, in the case can not reduce the number of threads, can only reduce the maximum heap and reduce the stack capacity to exchange for more threads.

Method area and run-time-constant pool overflow

Because the run-time-constant pool is part of the method area, it is put together.

The following code:

1  Public classruntimeconstantpooloom{2      Public Static voidMain (string[] args) {3list<string> list =NewArraylist<string>();4         intI =0;5          while(1)6List.add (String.valueof (i++). Intern ());7     }8}

Set up VM args:-xx:permsize=10m-xx:maxpermsize=10m. String.intern () is a native method that, if the string constant pool already contains a string equal to this string object, returns a String object that represents the string in the pool: Otherwise, add the string contained in this string to the constant pool. and returns a reference to this string. As you can see from the results, the following message after OutOfMemoryError is: PermGen Space, which indicates that the run-time constant pool is part of the method area.

  Solution Ideas:

Method area overflow is a common memory overflow exception, a class to be collected by the garbage collector, the judgment condition is relatively harsh. In the dynamic generation of a large number of class applications, you need to pay particular attention to the recycling of classes, common scenarios are: a large number of JSP or dynamically generated JSP file applications, OSGi-based applications and the use of Gglib bytecode enhancement (currently many mainstream framework spring, Hibernate uses bytecode technology like gglib) and dynamic languages.

Native Direct Memory Overflow

The directmemory capacity can be specified by-xx:maxdirectmemorysize, as is not specified, and the default is the same as the Java heap maximum value.

Paste the following code:

1  Public classdirectmemroyoom{2 3      Public Static Final int_1MB = 1024 * 1024;4 5      Public Static voidMain (string[] args)throwsexception{6Field Unsafefield = Unsafe.class. Getdeclarefields () [0];7Unsafefield.setaccessible (true);8unsafe unsafe = (unsafe) unsafefield.get (NULL);9          while(1)Ten unsafe.allocatememory (_1MB); One     } A}

Specify VM Args:-xmx20m-xx:maxdirectmemorysize=10m, the code crosses the Directbybuffer class and gets the unsafe instance directly through reflection for memory allocation. This is done because although allocating memory using Directbytebuffer also throws a memory overflow exception, the exception thrown does not really apply to the operating system to allocate memory, but by calculating that the memory cannot be allocated, and then manually throwing an exception, The real way to apply for memory is unsafe.allocatememory ().

  Solution Ideas:

Since this memory overflow is an obvious feature of the heap dump file will not see the obvious exception, if you find that the dump file is small, and the program directly or indirectly using NIO, then you can consider whether the native memory directly overflow.

The above is a summary of the Java memory overflow related, if there is not the place, welcome to point out, we communicate together.

  

PS: This blog welcome forwarding, but please specify the blog address and author ~

Blog Address: http://www.cnblogs.com/voidy/

<. ))) ≦ 

Simple analysis of Java OutOfMemoryError

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.