Effective Java (6) How to eliminate outdated object references

Source: Internet
Author: User

First, the introduction

Many people may be thinking of the problem: Java has garbage collection mechanism, then there are memory leaks? The answer is yes, the so-called garbage collection GC automatically manages memory recycling without requiring programmers to manually free up memory every time, but if there are a large number of temporary objects that do not need to be used without canceling a reference to them, they consume a large amount of memory, which can quickly result in a memory overflow.

Second, Java garbage collection mechanism

Objects in Java are allocated in the heap, and objects are created in 2 ways: new or reflective. Objects are recycled through the garbage collector, the JVM's garbage collector simplifies the programmer's work, but it adds to the JVM's work, which is one of the reasons why Java programs run slightly slower, because the GC must monitor the running state of each object, including the object's request, reference, referenced, Assignment, the GC will be monitored, monitoring the object's state is to more accurately and timely release of objects, and the fundamental principle of releasing objects is that the object is no longer referenced.

Three, memory leaks in Java

Memory leak objects have the following two features:

① These objects are accessible, that is, there are pathways in the direction graph that can be connected to them.

② These objects is useless, that is, the program will no longer use these objects.

public class Stack {  
    private final static int max_attribute = ten;  
    Private object[] arr;  
    private int index = 0;;  
      
    public void push (Object obj) {  
        if (Index > 9)  
            throw new IllegalArgumentException ();  
        Arr[index] = obj;  
        index++;  
    }  
      
    Public Stack () {  
        arr = new Object[max_attribute];  
    }  
      
    Public Object pop () {  
        if (Index < 0)  
            throw new IllegalArgumentException ();  
        return arr[--index];  
    }  

What happened to the memory leak in this program? If a stack grows and then shrinks, the objects that are popped from the stack will not be garbage collected, and even if the program using the stack no longer references those objects, they will not be recycled because the stack internally maintains the expired references to those objects.

Public Object pop () {    
    if (size = = 0)    
        throw new Emptystackexception ();    
    Object result = Elements[--size];    
    Elements[size] = null; Eliminate obsolete reference return result       
    ;    
}

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

WORKAROUND: Whenever an element is ejected from the stack, the reference is empty and the GC is recycled.

Four, common memory leaks

The use of static collection classes like HashMap, Vector, and ① is most likely to cause memory leaks because the lifecycle of these static variables is consistent with the application.

vector<object> vector = new vector<object> (a);   
for (int i = 1; i < i++) {  
    Object obj = new Object ();   
    Vector.add (obj);  
    obj = null;  
}

If you put an object into a vector, if you only release the reference itself, but the vector still references the object, then the object is not recyclable for the GC, and if you want to recycle it, the simplest thing to do is to set the vector object to null.

② in Java programs, we often have to deal with listeners, often calls such as Addxxxlistener () and other methods to increase the listener, but often forget to remove these listeners, thereby increasing the chance of memory leaks.

③ When using connection pooling, you must explicitly close the ResultSet and statement objects in addition to explicitly closing the connection. Otherwise, a large number of these objects will not be released, causing a memory leak.

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.