Java garbage collection mechanism and Memory leakage

Source: Internet
Author: User

Java garbage collection mechanism and Memory leakage

 

 

Original article address

Preface

On segmentfault, we can see a problem: java has a sound GC mechanism, so whether there will be a memory leakage problem in java, and whether a memory leakage case can be provided. This question view provides the complete answer to this question.

 

Introduction to the garbage collection mechanism

Each time an object is created, a certain amount of memory is allocated to store the object data. If you only keep allocating memory, the program will face insufficient memory sooner or later. Therefore, in any language, there will be a memory recycler to release the memory of expired objects to ensure that the memory can be reused.

The memory reclaim mechanism can be divided into two types based on different implementation roles. One is that the programmer manually releases the memory (such as the C language) the other is the built-in memory collection mechanism of the language, such as the java garbage collection mechanism described in this article.

 

Java garbage collection mechanism

In the runtime environment of the program, the Java Virtual Machine provides a system-level garbage Collection (GC, Carbage Collection) thread, which is responsible for recycling the memory occupied by the loss of referenced objects. The premise of understanding GC is to understand some concepts related to garbage collection. The following describes these concepts one by one.

 

State of the object in the jvm heap

Java object instances are stored in the jvm heap. For GC threads, these objects have three states.

1. touchable status: if there is a variable reference in the program, this object is touchable.

2. Recoverable state: when no variable in the program references this object, the object is changed from a touchable state to a recoverable state. The CG thread will prepare to call the finalize method of this Object at a certain time (the finalize method inherits or overwrites the sub-Object). The code in the finalize method may convert the Object to a touchable state, otherwise, the object is converted to inaccessibility.

3. inaccessibility: GC threads can reclaim the memory of an object only when the object is inaccessibility.

 

Jvm heap object state conversion

To release objects correctly, GC must monitor the running status of each object, including application, reference, reference, and assignment of objects. GC must monitor all objects, therefore, GC will know whether an object is in any state above.

As mentioned above, the GC thread will execute the finalize method of the Resurrected State object at a certain time. So when will it be executed? Different JVM implementers may use different algorithms to manage GC, so at any time, the developer cannot predict the time when the GC thread performs various operations (including checking the object status, releasing the object memory, and calling the finalize method of the object. Although the System. gc () and Runtime. gc () functions can be used to remind the GC thread to perform garbage collection as soon as possible, this does not guarantee that the GC thread will immediately perform corresponding garbage collection operations.

 

Memory leakage

Memory leakage refers to the failure to release memory that is no longer in use due to incorrect design, resulting in a waste of resources. GC automatically clears the memory occupied by the referenced objects. However, memory leakage may occur if some objects are always referenced due to program design errors.

For example, the following example. An array is used to implement a stack. There are two operations: Inbound stack and outbound 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];} // publ Ic void push (Object o) {capacity (); elements [size ++] = o ;}// public Object pop () {if (size = 0) throw new EmptyStackException (); return elements [-- size];} // increase the stack capacity 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 <100; I ++) stack. push (new Integer (I); for (int I = 0; I <100; I ++) {System. out. println (stack. pop (). toString ());}}}


 

This program is available and supports common inbound and outbound operations. However, one problem is not handled properly, that is, when the stack operation is performed, the reference of the stack elements in the array is not released, as a result, the program will keep referencing this Object (this object is referenced by an array). GC will always think that this Object is touchable, so it will not be able to release its memory. This is a typical case of Memory leakage. The modified code is as follows:

 

// Public Object pop () {if (size = 0) throw new EmptyStackException (); Object o = elements [-- size]; elements [size] = null; return o ;}


 

 

 

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.