Java memory overflow and Memory leakage

Source: Internet
Author: User

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

Recently, I have collected some information on the Internet, which is as follows:

I. Why do I need to know about memory leakage and memory overflow?

1. Memory leakage is generally caused by code design defects. By understanding the memory leakage scenario, you can avoid unnecessary memory overflow and improve your code writing level;

2. By understanding several common cases of memory overflow, you can quickly locate the problem in case of memory overflow and shorten the troubleshooting time.

Ii. Basic Concepts

Understanding these two concepts is very important.

Memory leakage: Indicates that the program dynamically allocates memory to some temporary objects, but the objects are not recycled by GC, which always occupies the memory. That isThe assigned object is reachable but useless..

Memory Overflow: Indicates that the program is runningCannot apply for enough memoryAn error. Memory overflow usually occurs after garbage collection of the OLD or Perm segments, and there is still no memory space to accommodate new Java objects.

From the definition, we can see thatMemory leakage is a cause of memory overflow.Is not the only factor.

Iii. Memory leakage scenarios:

1. Long Life Cycle objects hold references of short life cycle objects

This is the most common scenario of Memory leakage and a common problem in code design.

For example, if local variables are cached in a Global static map without being cleared, the map will become larger and larger over time, resulting in Memory leakage.

2. Modify the parameter value of an object in a hashset and the parameter is a field used to calculate the hash value.

When an object is stored in a HashSet set, you cannot modifyFields involved in calculating the hash valueOtherwise, the modified hash value of the object is different from the hash value originally stored in the HashSet set. In this case, even if the contains method uses the current reference of this object as the parameter to retrieve the object from the HashSet set, the results of the object not found will be returned, this will also cause the failure to delete the current object from the HashSet set, resulting in Memory leakage.

3. Machine connections and shutdown time settings

Enabling resource-consuming connections for a long time also results in Memory leakage.

Iv. memory overflow:

1. heap memory overflow(OutOfMemoryError: java heap space)

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

If subdivided, heap memory can also be divided into the young generation and the old generation. The young generation includes an eden zone and two vor zones.

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

A. jvm first tries to allocate the memory required for the new object in the eden area;

B. If the memory size is sufficient, the application is completed. Otherwise, the next step is required;

C. When jvm starts youngGC, it tries to release inactive objects in the eden area. If the Eden space is insufficient for new objects, try to put some active objects in Eden into the same vor area;

D. The primary vor area is used as the intermediate swap area of Eden and old. When the OLD area has sufficient space, objects in the primary vor area will be moved to the Old area; otherwise, objects in the primary vor area will be retained;

E. When the space in the OLD area is insufficient, the JVM will perform full GC in the OLD area;

F. After full GC, if the primary VOR and OLD areas still cannot store some objects copied from Eden, the JVM cannot create a memory area for the new object in the Eden area, "out of memory error" appears ":

OutOfMemoryError: java heap space

Code example:

/*** Heap memory overflow ** jvm parameter:-Xms5m-Xmx5m-Xmn2m-XX: newSize = 1 m **/public class MemoryLeak {private String [] s = new String [1000]; public static void main (String [] args) throws InterruptedException {Map
 
  
M = new HashMap
  
   
(); Int I = 0; int j = 10000; while (true) {for (; I
   
    

2. Method zone memory overflow(OutOfMemoryError: permgem space)

In the jvm specification, the method area mainly stores class information, constants, static variables, and so on.

So if the programToo many classes are loaded, or reflection and gclib are used.This kind of dynamic proxy generation technology may cause memory overflow in the zone. Generally, the error message when memory overflow occurs in the zone is:

OutOfMemoryError: permgem space

Code example:

Jvm parameter:-XX: PermSize = 2 m-XX: MaxPermSize = 2 m set the size of the method area to a very low level. When the class library is started, insufficient memory occurs.


3. Thread Stack Overflow(Java. lang. StackOverflowError)

A memory structure exclusive to the thread during the thread stack, so the thread stack issue must be an error generated when a thread is running.

Generally, thread stack overflow is causedToo deep recursion or too many call levels.

Stack overflow error message:

Java. lang. StackOverflowError

Code example:

/*** Thread operation Stack Overflow ** parameter:-Xms5m-Xmx5m-Xmn2m-XX: newSize = 1 m-Xss64k **/public class StackOverflowTest {public static void main (String [] args) {int I = 0; digui (I );} private static void digui (int I) {System. out. println (I ++); String [] s = new String [50]; digui (I );}}

5. To avoid Memory leakage, you can refer to the following suggestions during code writing:

1. Release reference of useless objects as soon as possible

2. Use String processing to avoid using String. Use StringBuffer in large quantities. Each String object must occupy an independent area of memory.

3. Use as few static variables as possible, because static variables are stored in the permanent generation (method area) and permanent generation is basically not involved in garbage collection.

4. Avoid creating objects in a loop

5. enable large files or take too much data from the database at a time, which may easily cause memory overflow. Therefore, you need to calculate the maximum data volume in these areas, set the minimum and maximum memory space values.

Refer:

Http://zhidao.baidu.com/question/263477119.html

Https://www.ibm.com/developerworks/cn/java/l-JavaMemoryLeak/ Java Memory leakage

Analysis of http://jelly-x.iteye.com/blog/1120406 JVM memory and memory overflow

Http://wenku.baidu.com/view/ef3158fc04a1b0717fd5ddda.html java Memory leakage and memory overflow

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.