Why the garbage collection mechanism in Java does not prevent memory leaks

Source: Internet
Author: User

First, this article refers to:1. In-depth understanding of Java Virtual Machine JVM advanced features and best practices 2. http://coderevisited.com/memory-leaks-in-java/Two, the object has been dead to determine the method of object recovery in the JVM first to determine whether the object is dead, the method of judgment is as follows: 1. The reference counting method gives object, the counter value is added 1 whenever there is a reference to it, and when the reference fails, the counter value is reduced by 1, and any object with a counter 0 at any time is impossible to be used again.      However, there is no reference counter algorithm in the mainstream Java virtual machine to manage memory, the main reason is that it is difficult to solve the problem of mutual circular reference between objects. 2. Accessibility analysis algorithm The basic idea of this algorithm is to use a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, the path of the search is called the reference chain, when an object to the GC Roots no reference chain connected, it proves that this object is not available.  As shown, objects Object5, OBJECT6, object7 are associated with each other, but they are not accessible to GC roots, so they will be judged as recyclable objects. Third, the case of memory leaks and code java heap memory leaks. is due to the fact that the Java object is not being created, but the object reference is not disposed. Here is a reference to the Java code, which is quoted from http://coderevisited.com/memory-leaks-in-java/ Class Com.code.revisited.memoryleaks.Stack provides some ways to implement the stack, including traversal, stack, and stack operations. Assume that the original purpose is for real use (this is, of course, to explain memory leaks).
 PackageCom.code.revisited.memoryleaks;ImportJava.util.Iterator;Importjava.util.NoSuchElementException;/** * @authorSureshsajja **/ Public classStack<e>ImplementsIterable<e> {    Private intN; Privatee[] Array; @SuppressWarnings ("Unchecked")     PublicStack (intcapacity) {Array= (e[])NewObject[capacity]; } @Override PublicIterator<e>iterator () {return NewStackiterator (); }    Private classStackiteratorImplementsIterator<e> {        Private inti = N-1; @Override Public BooleanHasnext () {returnI >= 0; } @Override PublicE Next () {if(!Hasnext ()) {                Throw Newnosuchelementexception (); }            returnarray[i--]; } @Override Public voidRemove () {Throw Newunsupportedoperationexception (); }    }     Public voidpush (E item) {if(Isfull ()) {Throw NewRuntimeException ("Stack Overflow"); } array[n++] =item; }     PublicE Pop () {if(IsEmpty ())Throw NewRuntimeException ("Stack underflow"); E Item= array[--N]; returnitem; }     Public BooleanIsEmpty () {returnN = = 0; }     Public intsize () {returnN; }     Public BooleanIsfull () {returnN = =Array.Length; }     PublicE Peek () {if(IsEmpty ())Throw NewRuntimeException ("Stack underflow"); returnArray[n-1]; }}

Class Com.code.revisited.memoryleaks.StackTest is used to perform stack operations. To be in the stack and out of the stack 10,000 operations, the ideal is to allocate heap memory when the stack, after the object is recycled.

 PackageCom.code.revisited.memoryleaks;/** * @authorSureshsajja **/ Public classStacktest {/**        * @paramargs*/         Public Static voidMain (string[] args) {Stack<Integer> s =NewStack<integer> (10000);  for(inti = 0; I < 10000; i++) {s.push (i); }                while(!S.isempty ())              {S.pop (); }                while(true ) {                      //Do something              }       }}
execution begins. We use VISUALVM to observe. In order to be more obvious, the stack operation part code comment is also executed.
 PackageCom.code.revisited.memoryleaks;/** * @authorSureshsajja **/ Public classStacktest {/**        * @paramargs*/         Public Static voidMain (string[] args) {//stack<integer> s = new stack<integer> (10000);//for (int i = 0; i < 10000; i++) {//S.push (i);//            }////While (!s.isempty ()) {//S.pop ();//            }                while(true ) {                      //Do something              }       }}

Set the stack operation to 1th number, no stack operation to the number 2nd, generate heap dump file Separately, we look at the class instance:

first of all, number 1th . first of all, number 2nd .It is obvious that the expected stack operation does not release the reference to the integer object (actually the code knows it), so it will not be recycled by GC.  The real reality this reference will be subtle, but it's always because the object is still referenced. Iv. conclusion This article only provides a brief description of the Java heap memory leak, and the next article discusses other related memory leaks. There's something wrong. Welcome to shoot Bricks >_<

Why the garbage collection mechanism in Java does not prevent 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.