Detailed description of Java Memory leakage causes

Source: Internet
Author: User

I. Java memory recovery mechanism
In either language, the actual address of the allocated memory must be returned, that is, the first address from the pointer to the memory block. In Java, objects are created using the new or reflection method. The creation of these objects is allocated in Heap, all objects are recycled by the Java Virtual Machine through the garbage collection mechanism. In order to release objects correctly, GC monitors the running status of each object, including their application, reference, reference, and assignment, java uses the directed graph method to manage the memory. If the real-time monitoring object can be reached, it will be recycled if it cannot be reached. This can also eliminate the issue of reference loops. In Java, two methods are used to determine whether a memory space complies with the garbage collection standard: one is to assign null values to the object, and no call has been made in the future, the other is to assign a new value to the object, which re-allocates the memory space.

Ii. Causes of Java Memory leakage
First, what is memory leakage? I often hear people talk about memory leaks, but I have to be clear about memory leaks. Memory leakage refers to the memory leakage caused by memory space waste because useless objects (objects that are no longer used) continuously occupy the memory or the memory of useless objects cannot be released in time. Memory leakage is sometimes not serious and hard to detect, so that developers do not know that there is a memory leak, but sometimes it will be very serious and will prompt you Out of memory.
So what is the root cause of Java Memory leakage? A reference to an object with a long life cycle holds a short life cycle, and memory leakage is likely to occur. Although a short life cycle object is no longer needed, however, a long life cycle object cannot be recycled because it is referenced by it. This is a scenario where memory leakage occurs in java. There are mainly the following categories:
1. Memory leakage caused by static collection classes:
The use of such static variables as HashMap and Vector is the most prone to memory leakage. The lifecycle of these static variables is the same as that of applications, and all objects referenced by them cannot be released, because they will always be referenced by Vector and so on.
Example:

Copy codeThe Code is 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 Object is applied cyclically and put into a Vector. If only the reference itself (o = null) is released, the Vector still references the Object, therefore, this object cannot be recycled for GC. Therefore, if an object is added to a Vector, it must be deleted from the Vector. The simplest way is to set the Vector object to null.

2. It does not work when the object attribute in the set is modified and the remove () method is called.

Example:

Copy codeThe Code is as follows: public static void main (String [] args)
{
Set <Person> set = new HashSet <Person> ();
Person p1 = new Person ("Tang Miao", "pwd1", 25 );
Person p2 = new Person ("Sun Wukong", "pwd2", 26 );
Person p3 = new Person ("", "pwd3", 27 );
Set. add (p1 );
Set. add (p2 );
Set. add (p3 );
System. out. println ("Total:" + set. size () + "elements! "); // Result: There are three elements in total!
P3.setAge (2); // modify the age of p3. The hashcode value corresponding to the p3 element changes.

Set. remove (p3); // at this time, the remove operation fails, causing memory leakage.

Set. add (p3); // re-add, actually added
System. out. println ("Total:" + set. size () + "elements! "); // Result: There are 4 elements in total!
For (Person person: set)
{
System. out. println (person );
}
}

3. Listener
In java programming, we all need to deal with listeners. Generally, many listeners are used in an application. We will call methods of controls such as addXXXListener () to increase listeners, however, when releasing objects, you often do not remember to delete these listeners, which increases the chance of Memory leakage.

4. Various connections
For example, database connection (connector se. getConnection (), network connection (socket) and io connections, unless it explicitly calls its close () method to close the connection, otherwise it will not be automatically recycled by GC. The Resultset and Statement objects can be explicitly recycled, but the Connection must be explicitly recycled, because the Connection cannot be automatically recycled at any time, and once the Connection is recycled, the Resultset and Statement objects are immediately NULL. However, if you use a connection pool, the situation will be different. In addition to explicitly closing the connection, you must also explicitly close the Resultset Statement object (close one of them, and the other will also close ), otherwise, a large number of Statement objects cannot be released, causing memory leakage. In this case, the connection is usually released in try, and the connection is released in finally.

5. Internal class and external module references
The reference of internal classes is relatively easy to forget, and once not released, a series of subsequent class objects may not be released. In addition, the programmer must be careful with the accidental reference of external modules. For example, programmer A is responsible for module A and calls A method of Module B, for example:
Public void registerMsg (Object B );
This kind of call should be very careful. If an object is passed in, it is very likely that Module B maintains the reference to this object. At this time, you need to pay attention to whether Module B provides the corresponding operation to remove the reference.

6. Singleton Mode
Improper use of the singleton mode is a common problem that causes memory leakage. A singleton object will exist throughout the JVM lifecycle after being initialized (in the form of static variables ), if a singleton object holds an external object reference, this external object cannot be recycled normally by jvm, leading to memory leakage. Consider the following example:

Copy codeThe Code is as follows: class {
Public (){
B. getInstance (). setA (this );
}
....
}
// Class B adopts the singleton Mode
Class B {
Private A;
Private static B instance = new B ();
Public B (){}
Public static B getInstance (){
Return instance;
}
Public void setA (A ){
This. a =;
}
// Getter...
}

Obviously, B adopts the singleton mode. It holds A reference to an object A, and the object of this Class A cannot be recycled. Imagine what would happen if A is A complex object or set 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.