Java Memory leakage

Source: Internet
Author: User

Troubleshoot Java memory leaks
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 meets the garbage collection standard: one is to assign null values to the object, and the following are not called, the other is to assign a new value to the object, which re-allocates the memory space.

Ii. Causes of Java Memory leakage
Root Cause of Java Memory leakage: Memory leakage is likely to occur when a long-lived object holds a reference to a short-lived object. Although short-lived objects are 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:
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:
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: 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 is 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 be closed). Otherwise, a large number of statement objects cannot be released, resulting in 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:

Class {
Public (){
B. getinstance (). Seta (this );
}
....
}
// Class B adopts the singleton Mode
Class B {
Private;
Private Static B instance = new B ();
Public B (){}
Public static B getinstance (){
Return instance;
}
Public void Seta (){
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.

Iii. Summary:
The above sections also inspire us to look for memory leaks and focus on long-lived objects during code review: global sets (variables) use of Singleton mode, static variables of the class, and so on. In the implementation process of Java, we also need to consider the release of its objects. The best way is to explicitly leave this object blank when no object is used. It is best to follow the principle of who created and released.

From http://xgtxxxx.iteye.com/blog/1622236

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.