Java memory overflow and memory leaks

Source: Internet
Author: User

Although the JVM can automatically reclaim useless memory through GC, there is still a risk of memory overflow if the code is not good.

Recently collected some information on the Internet, now collated as follows:

——————————————————————————————————————————

First, why should we understand memory leaks and memory overflows?

1, memory leakage is generally a defect in code design, through the understanding of memory leakage scenarios, you can avoid unnecessary memory overflow and improve their coding level;

2, through the understanding of several common memory overflow situation, can be in memory overflow when the location of the problem quickly, shorten the time to resolve the failure.

Ii. Basic Concepts

It is important to understand these two concepts.

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 .

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.

From the definition, it can be seen that the internal leakage is an inducement of memory overflow , not the only factor.

Three, memory leakage of 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.

Four, memory overflow of several situations:

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

code example:

<span style= "FONT-SIZE:11PX;" >/*** Heap Memory Overflow * * JVM parameters:-xms5m-xmx5m-xmn2m-xx:newsize=1m**/ Public classMemoryleak {PrivateString[] s =Newstring[1000];  Public Static voidMain (string[] args)throwsinterruptedexception {Map<String,Object> m =NewHashmap<string,object>(); intI =0; intj=10000;  while(true){             for(; i<j;i++) {Memoryleak memoryleak=NewMemoryleak ();            M.put (String.valueof (i), memoryleak); }        }    }}</span>

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

code example:

<span style= "FONT-SIZE:11PX;" >/*** Thread Operation Stack Overflow * * parameter:-xms5m-xmx5m-xmn2m-xx:newsize=1m-xss64k**/ Public classStackoverflowtest { Public Static voidMain (string[] args) {intI =0;    Digui (i); }       Private Static voidDigui (inti) {System.out.println (i++); String[] s=NewString[50];    Digui (i); }}</span>

V. What is the cause of memory overflow

Memory overflow is due to the fact that there are too many objects (garbage) that are not referenced to cause the JVM to recycle, causing a memory overflow. If this behavior occurs, troubleshoot the code:

A) whether the static decorations such as public STAITC Student s are used too much in classes and reference variables in the app, and it is best to use the static adornment in the properties of the class with only the base type or string. such as public static int i = 0; public static String str;

b) Whether the app uses a large number of recursive or infinite recursion (recursive use of a large number of new objects built)

III) whether the app uses a lot of loops or loops (a lot of new objects are used in the loop)

IV) Check whether the app uses a method that queries all records to the database. That is, a one-time full query method, if the amount of data more than 100,000, it can cause memory overflow. Therefore, a "paged query" should be used when querying.

Five) Check if there are arrays, where the List,map is the object's reference, not the object, because these references cause the corresponding object to not be freed. are stored in memory in large quantities.

VI) Check whether to use the "non-literal string for +" operation. Because the contents of the string class are immutable, a new object is generated each time the "+" is run, and if too many new string objects are created, a memory overflow occurs that causes the JVM not to be reclaimed in a timely manner.

such as String S1 = "My name";

String s2 = "is";

String s3 = "Xuwei";

String str = s1 + s2 + s3 + ...; This can easily cause memory overflow.

But string str = ' My name ' + ' is ' + ' xuwei ' + ' nice ' + ' to ' + ' meet you '; However, this does not cause a memory overflow. Because this is a literal string, running "+" runs well during compilation. Do not follow the JVM.

When using String,stringbuffer,stringbuilder, string performance is preferable when the literal strings are "+", and if thread safety is not considered when the string class is "+". Should choose StringBuilder performance is better.

Six, in order to avoid memory leaks, in the process of writing code can refer to the following recommendations:

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.

Java memory overflow and memory leaks

Related Article

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.