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:

Java code
  1. <span style="font-size:11px;" >/**
  2. * Heap Memory Overflow
  3. *
  4. * JVM Parameters:-xms5m-xmx5m-xmn2m-xx:newsize=1m
  5. *
  6. */
  7. Public class Memoryleak {
  8. private string[] s = new string[1000];
  9. public static void Main (string[] args) throws interruptedexception {
  10. map<string,object> m =new hashmap<string,object> ();
  11. int i =0;
  12. int j=10000;
  13. While (true) {
  14. For (; i<j;i++) {
  15. Memoryleak memoryleak = new Memoryleak ();
  16. M.put (String.valueof (i), memoryleak);
  17. }
  18. }
  19. }
  20. }</span>
/*** Heap Memory Overflow * * JVM parameter:-xms5m-xmx5m-xmn2m-xx:newsize=1m**/public class Memoryleak {       private string[] s = new string[100 0];     public static void Main (string[] args) throws interruptedexception {        map<string,object> m =new hashmap< String,object> ();        int i =0;        int j=10000;        while (true) {for            (; i<j;i++) {                Memoryleak memoryleak = new Memoryleak ();                M.put (String.valueof (i), memoryleak);}}}    

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

code example:

Java code
    1. <span style="font-size:11px;" >JVM parameter:-xx:permsize=2m-xx:maxpermsize=2m
    2. The size of the method area is set very low, and there is an out-of-memory situation when you start loading the class library </span>
JVM parameter:-xx:permsize=2m-xx:maxpermsize=2m the size of the method area is set very low, there is an out-of-memory condition when you start loading the class library

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:

Java code
  1. <span style="font-size:11px;" >/**
  2. * Thread Operation Stack Overflow
  3. *
  4. * Parameter:-xms5m-xmx5m-xmn2m-xx:newsize=1m-xss64k
  5. *
  6. */
  7. Public class Stackoverflowtest {
  8. public static void Main (string[] args) {
  9. int i =0;
  10. Digui (i);
  11. }
  12. private static void Digui (int i) {
  13. System.out.println (i++);
  14. String[] s = new string[50];
  15. Digui (i);
  16. }
  17. }
  18. </span>
/*** thread Operation Stack Overflow * parameter:-xms5m-xmx5m-xmn2m-xx:newsize=1m-xss64k**/public class Stackoverflowtest {public       static void Ma In (string[] args) {        int i =0;        Digui (i);    }       private static void Digui (int i) {        System.out.println (i++);        String[] s = new string[50];        Digui (i);    }}

Five, 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.

Reference:

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

Https://www.ibm.com/developerworks/cn/java/l-JavaMemoryLeak/Java memory leaks

http://jelly-x.iteye.com/blog/1120406 JVM Memory analysis and causes memory overflow

http://wenku.baidu.com/view/ef3158fc04a1b0717fd5ddda.html Java memory leak and memory overflow

Java memory overflow and memory leaks

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.