Detailed description of Java memory leak reason _java

Source: Internet
Author: User
Tags connection pooling garbage collection object object

Java Memory Recovery mechanism
Regardless of the type of memory allocation, you need to return the actual address of the allocated memory, which is to return a pointer to the first address of the memory block. Objects in Java are created using new or reflective methods, which are created in the heap (Heap), and all objects are recycled by the Java virtual machine through the garbage collection mechanism. GC in order to properly release objects, will monitor the health of each object, their applications, references, referrals, assignments, and other conditions of monitoring, Java will use a method of mapping to manage memory, real-time monitoring of the object can be achieved, if not reachable, it will be recycled, This can also eliminate the problem of reference loops. In the Java language, there are two criteria for determining whether a single memory space is eligible for garbage collection: one is to give the object a null value NULL, not to call it later, another to give the object a new value, so that the memory space is reallocated.

Second, Java memory leaks cause
First, what is a memory leak? Often hear people talk about memory leaks, but to ask what is the memory leak, few say clearly. A memory leak is a waste object (objects that are no longer in use) that continuously occupies memory or the memory of unwanted objects is not released in a timely manner, resulting in the wasting of memory space called memory leaks. Memory leaks are sometimes not severe and difficult to detect, so developers do not know that there is a memory leak, but sometimes very serious, will prompt you out of the memory.
So what is the root cause of Java memory leaks? A long lifecycle object holds a reference to a short lifecycle object and is likely to have a memory leak, although the short lifecycle object is no longer needed, but because the long lifecycle object holds its reference and cannot be reclaimed, this is the scenario where memory leaks occur in Java. There are several major categories:
1. Static collection classes cause memory leaks:
The use of hashmap, vectors, and so on is the most vulnerable to memory leaks, and the lifecycle of these static variables is consistent with the application, and all object objects referenced by them cannot be released because they will also be referenced by vectors.
Cases:

Copy Code code as follows:

Static vector v = new vector (10);
for (int i = 1; i<100; i++)
{
Object o = new Object ();
V.add (o);
o = null;
}//

In this example, the loop applies the object object and puts the applied objects into a vector, and if only the reference itself (O=null) is released, the vector still references the object, so the object is not recyclable for the GC. Therefore, if the object is added to the vector, it must also be removed from the vector, and the simplest way is to set the vector object to null.

2. When the object attribute in the collection is modified, the Remove () method is not effective.

Cases:

Copy Code code as follows:

public static void Main (string[] args)
{
set<person> set = new hashset<person> ();
person P1 = new Person ("Tang Seng", "Pwd1", 25);
person P2 = new Person ("Monkey King", "Pwd2", 26);
Person P3 = new person ("pig", "pwd3", 27);
Set.add (p1);
Set.add (p2);
Set.add (p3);
System.out.println ("A total of:" +set.size () + "Element!"); Results: Total: 3 Elements!
P3.setage (2); Modify the age of the P3, at which point the hashcode value of the P3 element changes

Set.remove (p3); The remove is not removed at this time, causing a memory leak

Set.add (p3); Re-add, incredibly add success
System.out.println ("A total of:" +set.size () + "Element!"); Results: Total: 4 Elements!
for (person Person:set)
{
SYSTEM.OUT.PRINTLN (person);
}
}

3. Listener
In Java programming, we all need to deal with the listener, usually in an application will use a lot of listeners, we will call a control such as Addxxxlistener () and other methods to increase the listener, but often in the release of the object did not remember to delete these listeners, This increases the chance of memory leaks.

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 turn its connection off. For Resultset and statement objects, no explicit collection can be made, but connection must be explicitly recycled because connection cannot be automatically recycled at any time, and connection once recycled, Resultset and statement objects are immediately null. However, if you use connection pooling, the situation is different, in addition to explicitly shutting down the connection, you must explicitly close the ResultSet Statement object (either close one and the other will close), otherwise a large number of Statement objects will not be released, causing a memory leak. In this case, the connection is generally going to be in the try, releasing the connection in finally.

5. References to internal classes and external modules, etc.
References to internal classes are more easily forgotten and, once not released, can result in a series of subsequent class objects not being released. In addition, programmers have to be careful of the external module inadvertently referenced, such as programmer A is responsible for a module, called the B module of a method such as:
public void registermsg (Object b);
This call must be very careful, passing in an object, it is likely that module B to maintain a reference to the object, this time you need to pay attention to module B to provide appropriate action to remove the reference.

6. Single Case mode
Improper use of single case mode is a common problem that causes memory leaks. A single Instance object is initialized to exist throughout the JVM's lifecycle (in the form of static variables), and if a single instance object holds a reference to an external object, the external object will not be properly reclaimed by the JVM, causing memory leaks. Consider the following example:

Copy Code code as follows:

Class a{
Public A () {
B.getinstance (). SetA (this);
}
....
}
Class B Using a single case model
Class b{
Private a A;
private static B Instance=new B ();
Public B () {}
public static B getinstance () {
return instance;
}
public void SetA (a) {
This.a=a;
}
Getter ...
}

Obviously b uses the singleton mode, it holds a reference to a object, and the object of Class A cannot be reclaimed. Imagine what happens if a is a more complex object or collection type.

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.