Explanation of Java memory leaks

Source: Internet
Author: User
Tags connection pooling

First, the Java Memory recovery mechanism
Regardless of the memory allocation in any language, it is necessary to return the actual address of the allocated memory, that is, to return a pointer to the first address of the memory block. Objects in Java are created using new or reflected methods, which are created in the heap, and all objects are reclaimed by the Java virtual machine through a garbage collection mechanism. In order to properly dispose of objects, the GC monitors the health of each object, monitors their applications, references, references, assignments, and so on, and Java uses a graph-like approach to manage memory, real-time monitoring of whether objects can be reached, and if not, to recycle them. This can also eliminate the problem of reference loops. In the Java language, there are two criteria for determining if a memory space is eligible for garbage collection: one is to give the object null value, the following is not called again, and the other is to give the object a new value, so that the memory space is reallocated.

Ii. causes of Java memory leaks
First, what is a memory leak? Often listen to people talking about memory leaks, but to ask what is a memory leak, not a few speak clearly. Memory leaks refer to useless objects (objects that are no longer being used) that persist in memory or the memory of useless objects is not released in a timely manner, resulting in a waste of memory space known as memory leaks. Memory leaks are sometimes not critical and imperceptible, so developers do not know that there is a memory leak, but sometimes it can be very serious and will prompt you out of your memory.
So what is the root cause of the Java memory leak? Long life-cycle objects that hold references to short life-cycle objects are likely to have a memory leak, although a short life-cycle object is no longer needed, but because a long-life-cycle object holds its reference and cannot be recycled, this is the scenario where memory leaks occur in Java. There are several major categories:
1. A static collection class causes a memory leak:
Uses such as HashMap, vectors, and so on are the most prone to memory leaks, and the lifetime of these static variables is consistent with the application, and all objects referenced by them cannot be freed because they will always be referenced by vectors.
Cases:
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 to 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.

(1) If you want to release the object, you must make its reference count of 0, only those objects that are no longer referenced can be freed, this principle is very simple, but very important, is the basic cause of memory leaks, but also the purpose of resolving the memory leak method;
(2) The programmer does not need to manage the object space specific allocation and release process, but must pay attention to the released object's reference count is 0;
(3) A few of the procedures that an object may be referenced by another object:


A. Direct assignment, as in the above example A.A = E;
B. Pass through parameters, such as public void AddObject (Object E);
C. Other situations, such as system calls.

2. When the object property inside the collection is modified, the Remove () method does not work when it is called.

Cases:
public static void Main (string[] args)
{
set<person> set = new hashset<person> ();
person P1 = new Person ("Tang Monk", "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 () + "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 changes

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

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

3. Listener
In Java programming, we all need to deal with listeners, usually one 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 objects without remembering 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 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 connection is usually going in the try and releasing the connection in finally.

5. References to internal classes and external modules, etc.
The reference to the inner class is a relatively easy one to forget, and once it is not released it can cause a series of subsequent class objects not to be released. In addition, the programmer should be careful of the external module inadvertently referenced, such as programmer A is responsible for a module, a method called the B module, such as:
public void registermsg (Object b);
This call will be very careful, passing in an object, it is likely that module B will maintain a reference to the object, it is important to note that Module B provides the appropriate action to remove the reference.

6. Single case Mode
Improper use of Singleton mode is a common problem that causes memory leaks, where a singleton object will exist in the JVM's lifetime (in the form of a static variable) after it is initialized, and if the Singleton object holds a reference to an external object, the external object will not be properly reclaimed by the JVM, causing a memory leak. Consider the following example:
Class a{
Public A () {
B.getinstance (). SetA (this);
}
....
}
Class B with single-case mode
Class b{
Private a A;
private static B Instance=new B ();
Public B () {}
public static B getinstance () {
return instance;
}
public void SetA (a a) {
This.a=a;
}
Getter ...
}
Obviously B uses the singleton pattern, which holds a reference to a object, and the Class A object cannot be recycled. Imagine what happens if a is a more complex object or a collection type.

Explanation of Java 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.