Java garbage collection mechanism and memory leaks

Source: Internet
Author: User



Original address


Objective

See a question on Segmentfault: Java has a well-developed GC mechanism, so whether there will be a memory leak in Java, and can give a case of a memory leak. This problem view gives a complete answer to this question.


Introduction to garbage collection mechanism

During a program's run, each object created is allocated a certain amount of memory to store the object data. If you just keep allocating memory, the program will sooner or later face an out-of-memory problem. So in any language, there is a memory recycling mechanism to free memory of outdated objects to ensure that memory can be reused.

The memory recycling mechanism can be divided into two kinds according to the implementation of the role, one is the programmer to manually implement the release of memory (such as the C language) the other is the language built-in memory recycling mechanism, such as this article will introduce the Java garbage collection mechanism.


Java's garbage collection mechanism

In the run-time environment of the program, the Java Virtual Machine provides a system-level garbage collection (Gc,carbage Collection) thread that is responsible for reclaiming memory that is consumed by objects that are not referenced. The premise of understanding GC is to understand some of the concepts related to garbage collection, which are described below.


The state of the object in the JVM heap area

Instances of Java objects are stored in the heap area of the JVM, and for GC threads, there are three states of these objects.

1. Accessible state: There is also a variable reference in the program, then this object is accessible.

2. The Resurrection State: when there are no variables in the program that refer to this object, the object is moved from the accessible state to the resurrected state. CG threads will be ready to call this object's Finalize method at a certain time (the Finalize method inherits or overrides the child object), and the code within the Finalize method may turn the object into a reachable state, otherwise the object is converted to a non-reachable state.

3. Unreachable state: The GC thread can reclaim the memory of this object only if the object is in a non-accessible state.


JVM Heap Area Object state transitions

In order for the GC to be able to properly dispose of objects, it is necessary to monitor the running state of each object, including the application, reference, reference, assignment, etc. of the object, and the GC needs to be monitored, so no matter what state the GC will be aware of in any of the states above.

As mentioned above, when a GC thread executes a finalize method of a resurrected state object at a certain time, when does it execute? Since different JVM implementations may use different algorithms to manage GC, at any time the developer cannot anticipate the timing of the GC thread's operations (including detecting object state, freeing object memory, and invoking the object's Finalize method). Although it is possible to alert GC threads to garbage collection operations as soon as possible through the System.GC () and RUNTIME.GC () functions, there is no guarantee that GC threads will be recycled immediately.


Memory leaks

A memory leak is a waste of resources due to faulty design that causes the program to fail to release memory that is no longer in use. The GC automatically cleans up memory used by objects that are not referenced. However, some objects are always referenced because of a programming error, and a memory leak occurs.

Like the example below. Using an array to implement a stack, there are two operations in the stack and out of the stack.

Import Com.sun.javafx.collections.elementobservablelistdecorator;import Com.sun.swing.internal.plaf.metal.resources.metal_sv;import Java.beans.exceptionlistener;import java.util.emptystackexception;/** * Created by Peng on 14-9-21.    */public class Mystack {private object[] elements;    private int Increment = 10;    private int size = 0;    public mystack (int size) {elements = new object[size];        }//into the stack public void push (Object o) {capacity ();    elements[size++] = o;        }//out-of-stack public Object pop () {if (size = = 0) throw new emptystackexception ();    return elements[--size];        }//Increase the capacity of the stack private void capacity () {if (elements.length! = size) return;        object[] NewArray = new Object[elements.length + Increment];    System.arraycopy (elements, 0, NewArray, 0, size);        } public static void Main (string[] args) {Mystack stack = new Mystack (100);       for (int i = 0; i <; i++)     Stack.push (New Integer (i));        for (int i = 0; i < i++) {System.out.println (Stack.pop (). toString ()); }    }}


This program is available to support commonly used in-stack and out-stack operations. However, there is one problem that is not handled well, that is, when the stack operation is not released, it does not release the reference to the stack element in the array, which causes the program to keep a reference to the object (this object is referenced by the array), and the GC will always think that it is reachable, and it is much less free of its memory. This is a typical case of memory leaks. For this, the modified code is:

Out-of-stack public    Object pop () {        if (size = = 0)            throw new Emptystackexception ();        Object o = elements[--size];        Elements[size] = null;        return o;    }



Information

Ibmdeveloper worker: http://www.ibm.com/developerworks/cn/java/l-JavaMemoryLeak/

Sun Weichen "Java Object-oriented programming"

Java garbage collection mechanism and memory leaks

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.