Memory overflow and memory leaks

Source: Internet
Author: User

1. Basic Concepts

Memory overflow: Simply said memory overflow means that the program is running in the process of requesting more memory than the system can provide memory, resulting in the inability to request enough memory , and then a memory overflow occurred.

Memory leaks: Memory leaks are memory leaks that occur when a program runs to allocate memory to temporary variables, is not recycled by GC , is always occupied with memory, cannot be used, and cannot be assigned to other programs.

2. Common scenarios of memory overflow

There are several common scenarios for memory overflow:

(1) Java.lang.OutOfMemoryError:PermGen space (persistent with overflow)

We know that the JVM implements the method area in the Java Virtual Machine specification through the persistence band, and the run-time pool is stored in the method area, so this overflow can be a run-time pool overflow, or because a large number of jar or class is used in the program, The class object saved in the method area is not reclaimed in time or the class information occupies more memory than the configured size.

(2) Java.lang.OutOfMemoryError:Java heap space (heap overflow)

This overflow is typically caused by too many objects being created, and the number of objects reaches the maximum heap capacity limit before the garbage collection takes place.

The method of resolving this area anomaly is typically to analyze the dump dump snapshot through the memory image analysis tool to see if it is a memory overflow or a memory leak. If it is a memory leak, further through the tool to see the leaking object to the GC roots reference chain, locate the leak code location, modify the program or algorithm, if there is no leakage, that is, the objects in memory must still survive, you should check the virtual machine's heap parameters-xmx (maximum heap size) and-XMS ( The initial heap size), compared to the physical memory of the machine to see if it can be resized.

(3) Overflow of virtual machine stack and local method stack

If the thread requests a stack depth that is greater than the maximum allowed depth for the virtual machine, the Stackoverflowerror is thrown

Throws OutOfMemoryError if the virtual machine cannot request enough memory space on the scale stack

3. Memory leaks

The root cause of a memory leak is that long life-cycle objects hold references to short-life-cycle objects, although objects of short lifecycles are no longer needed, but cannot be recycled because long-life-cycle objects hold their references.

Several common memory leaks are summarized below:

(1) memory leaks due to static collection classes

The use of Hashtable is most prone to memory leaks, such as Hashmap,vector, where the life cycle of these variables is consistent with the program, and the objects they hold cannot be freed, causing a memory leak. As in the following example:

vector<object> v=New vector<object> (+);  for (int i = 1; i<100; i++newnull;}

The loop requests the object object and puts the requested objects into a vector, and if you just release the reference itself (O=null), then the vector still references the object, so the object is not recyclable to the GC. Therefore, if the object has to be removed from the vector after it has been added to the vector, the simplest way is to set the vector object to null.

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

When an object is stored in the HashSet collection, after modifying the field in the object that participates in the hash value, the hash value of the object is different from the one originally stored in the collection, in which case the Contains method is not found to retrieve the object in the collection. This will result in the inability to delete the current object from HashSet, causing a memory leak, for example:

 Public Static voidMain (string[] args) {Set<Person> set =NewHashset<person>(); Person P1=NewPerson ("Zhang San", "1", 25); Person P2=NewPerson ("John Doe", "2", 26); Person P3=NewPerson ("Harry", "3", 27); Set.add (p1); Set.add (p2); Set.add (p3); System.out.println ("A total of:" +set.size () + "Elements!");//results: Total: 3 elements!P3.setage (2);//modifies the age of P3, at which point the P3 element corresponds to a hashcode value that changesSet.remove (p3);//The Remove does not drop at this time, causing a memory leakSet.add (p3);//re-add, you can add successSystem.out.println ("A total of:" +set.size () + "Elements!");//results: Total: 4 Elements! for(person Person:set) {System.out.println (person);}}

Note: When implementing this example, pay attention to overriding the Hashcode method of the person class.

(3) Use of the listener

Usually a lot of listeners are used in an application, we call a control such as Addxxxlistener () to increase the listener, but often do not remember to delete the listener when releasing the object, thus increasing the chance of memory leak.

(4) Various connections

For example, a database connection (Datasourse.getconnection ()), a network connection (socket), and an IO connection are not automatically reclaimed by GC unless it explicitly calls its close () method to close its connection. For Resultset and statement objects can not be explicitly recycled, but connection must be explicitly recycled, because connection can not be automatically recycled at any time, and connection once recycled, Resultset And the statement object are immediately null. However, if you use connection pooling, the situation is different, in addition to explicitly closing the connection, you must also explicitly close the ResultSet Statement object (Close one, the other will also shut down), otherwise it will cause a large number of Statement objects can not be released, causing a memory leak. In this case, the general will be in the try to connect, in the finally inside release the connection.

Some suggestions to avoid memory leaks:

(1) Early release of references to useless objects

(2) Avoid creating objects in loops

(3) Avoid using string when working with strings, use StringBuffer

(4) Minimize the use of static variables, because static variables are stored in the permanent generation, basically do not participate in garbage collection

If there is any mistake or need to be supplemented, please advise me, thank you.

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.