Test Oom exception

Source: Internet
Author: User

One, Java heap overflow
Memory overflow and memory leaks

Memory overflow: An error caused by the inability to request enough memory during a program's run. Memory overflows typically occur after the old or perm segment garbage collection, and there is still no memory space to accommodate new Java objects.

Memory leak: Refers to the program in the dynamic allocation of memory to some temporary objects, but the object is not reclaimed by the GC, it always consumes memory. That is, the allocated object can be reached but is useless

Package Com.weixuan.outofmemory;import Java.util.arraylist;import java.util.list;/** *-verbose:gc-xms20m-xmx20m- XMN10M-XX:+PRINTGCDETAILS-XX:SURVIVORRATIO=8 *-xx:+heapdumponoutofmemoryerror * * @author Nicholas * java heap overflow * java heap To store object instances, as long as the object is constantly created, and the GC roots to the object has reachable paths to avoid the garbage collection mechanism to clear these objects * then a memory overflow exception occurs when the number of objects reaches the maximum heap capacity limit *//* *-xms20m: The minimum heap value is 20m *- xmx20m: Heap maximum value is 20m, the maximum and minimum values are the same, can avoid heap auto-expansion *-xmn10m: Cenozoic size is 10m *-xx:+printgcdetails: Print auxiliary information *-xx:survivorratio=8:java heap The ratio of Eden to Survivor is set to 8, the ratio of two survivor to one Eden area is 2:8, and a survivor area is the 1/10 of the entire young generation *-xx:+heapdumponoutofmemoryerror : When a memory overflow exception occurs, dump the current memory dump snapshot information for post-analysis *//** * How to handle heap memory overflow? * Open heap Memory dump file with EMA Eclipse Memory Analyzer * First to distinguish between memory leaks or memory leaks * If it is a memory leak: The tool looks through the reference chain of the leaked object to the GC roots and then finds out what path the compromised object is related to the GC roots and causes the garbage collector not to automatically reclaim their * if there is no leakage, that is, the object in memory is still alive, then you should check the virtual machine's heap parameters-xmx-xms can be adjusted appropriately * */public class Heapoom {static Class Oomobj ECT {}public static void main (string[] args) {list<oomobject> List = new ARRAYLIST&LT;HEAPOOM.OOMOBJECT&Gt; (); while (true) {List.add (New Oomobject ());}}} 

Second, virtual machine stack and local method stack Overflow

Package com.weixuan.outofmemory;/** * Virtual machine stack and local method stack Overflow *-xss128k * @author Nicholas * The virtual machine stack and the local method stack are not distinguished in the hotspot virtual machine that is, the-xoss parameter is not * Stack capacity is only set by the-XSS parameter * * in single-threaded case, whether the stack frame is too large or the virtual machine capacity is too small, when the memory can not be allocated when the Stackoverflowerror exception */public class Javavmstacksof {private int stacklength = 1;public void Stackleak () {stacklength++;stackleak ();} public static void Main (string[] args) {javavmstacksof javavmstacksof = new javavmstacksof (); try { Javavmstacksof.stackleak ();} catch (Throwable e) {System.out.println ("Stack Length:" + javavmstacksof.stacklength); throw e;}}}


Iii. method area and run-time constant pool overflow

Package Com.weixuan.outofmemory;import java.util.arraylist;import java.util.list;/** * Memory overflow for running a constant pool *-xx:permsize=10m -xx:maxpermsize=10m * @author Nicholas * Java 8 has removed the permanent generation from the method area *//** * Intern () is a native method * If the string constant pool already contains a string equal to this string object , the reference to the second String object is returned */public class Runtimeconstantpooloom {public void Testintern () {String string1 = new StringBuilder ("Computer "). Append (" Software "). ToString (); System.out.println (String1==string1.intern ()); String string2 = new StringBuilder ("Ja"). Append ("va"). toString (); System.out.println (String2==string2.intern ());} public static void Main (string[] args) {list<string> List = new arraylist<string> (); int i = 0;while (true) {Li St.add (String.valueof (i++). Intern ());}}}

Java 8 has removed the permanent generation from the method area


Four, native direct memory overflow


Package Com.weixuan.outofmemory;import java.lang.reflect.field;import sun.misc.unsafe;/** *-xms20m-xx: maxdirectmemorysize=10m * @author Nicholas * */public class Directmemoryoom {private static final int _1mb = 1024x768 * 1024;p Ublic static void Main (string[] args) {//TODO auto-generated method Stubfield Unsafefield = Unsafe.class.getDeclaredField S () [0];unsafefield.setaccessible (true); Unsafe unsafe = null;try {unsafe = (unsafe) unsafefield.get (null);} catch (IllegalArgumentException | Illegalaccessexception e) {e.printstacktrace ();} while (true) {unsafe.allocatememory (_1MB);}}}

V. Summary

Memory leaks in several scenarios: 1. Long life cycle objects hold references to short life cycle objects

This is the most common scenario for memory leaks and is a recurring problem in code design.

For example, in a global static map cache local variables, and there is no empty operation, over time, the map will grow larger, causing memory leaks.

2. Modify the parameter value of the object in HashSet, and the parameter is the field that computes the hash value

When an object is stored in the HashSet collection, it is not possible to modify those fields in the object that participate in the calculation of the hash value, otherwise the modified hash value of the object is different from the hash value originally stored in the HashSet collection, in which case Even if the Contains method uses the object's current reference as a parameter to retrieve an object in the HashSet collection, the result of the object cannot be found, which also results in the inability to remove the current object from the HashSet collection, causing a memory leak.

3, the machine's connection number and the shutdown time setting

Opening a very resource-intensive connection for a long time can also lead to memory leaks.

Memory overflow Scenarios: 1, heap memory overflow (Outofmemoryerror:java heap space)

In the JVM specification, memory in the heap is used to generate object instances and arrays.

If broken down, heap memory can also be divided into younger generations and older generations, including an Eden area and two survivor districts for younger generations.

When a new object is generated, the memory application process is as follows:

A, the JVM first attempts to allocate the memory required for new objects in the Eden area;

b, if the memory size is sufficient, the application ends, otherwise the next step;

C, the JVM initiates YOUNGGC, attempts to release the inactive objects in the Eden area, and if Eden space is still insufficient to place the new objects after release, attempts to put some of the active objects in Eden into the Survivor area;

D, Survivor area is used as the middle Exchange area of Eden and old, when the old area is enough space, the object of Survivor area will be moved to old area, otherwise it will be kept in survivor area;

E, when the old area is not enough space, the JVM will be in the old area full GC;

F, full GC, if the survivor and old areas still cannot hold portions of objects copied from Eden, causing the JVM to be unable to create memory areas for new objects in the Eden area, an "out-of-storage error" occurs:

Outofmemoryerror:java Heap Space

2. Method area Memory Overflow (outofmemoryerror:permgem space)

In the JVM specification, the method area mainly holds the class information, the constant, the static variable and so on.

So if a program loads too many classes, or uses such dynamic proxy generation techniques as reflection, gclib, and so on, it can cause a memory overflow in that area, which is generally the error message when a memory overflow occurs in this area:

Outofmemoryerror:permgem Space

3. Thread stack Overflow (java.lang.StackOverflowError)

Thread stacks a piece of memory structure that is unique to threads, so a thread stack problem must be an error that occurs when a thread is running.

Generic thread stack Overflow is caused by too much recursion or too many levels of method calls.

The error message that the stack overflow occurred is:

Java.lang.StackOverflowError

How to avoid memory leaks

1. Release references to useless objects as early as possible

2, use string processing, avoid using string, should use a lot of stringbuffer, each string object has to occupy a piece of memory area

3, minimize the use of static variables, because static variables stored in the permanent generation (method area), the permanent generation of basic non-participation in garbage collection

4. Avoid creating objects in loops

5. Opening large files or taking too much data from a database can easily cause memory overflow, so be sure to calculate the maximum amount of data in these places, and set the minimum and maximum memory space values required.

Test Oom exception

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.