Deep understanding of the Java garbage collection mechanism and memory leak _java

Source: Internet
Author: User
Tags garbage collection int size

Objective

See a problem on the Segmentfault: Java has a perfect GC mechanism, then in Java will be a memory leak problem, and can give a memory leak case. The full answer to this question is given in the view of this question.

Introduction to garbage collection mechanism

In the process of running a program, each object created will be allocated a certain amount of memory to store the object data. If you just keep allocating memory, then sooner or later the program will be facing a problem with insufficient memory. So in any language, there is a memory recycle mechanism to release the memory of expired objects to ensure that the memory can be reused.

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

Java's garbage collection mechanism

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

The state of the object in the JVM heap area

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

1. Accessible Status: The program also has a variable reference, then this object is accessible state.

2. The Resurrection State: When the program has no variables to reference this object, then this object from the touch state to the Resurrection State. The CG thread will be ready to call the Finalize method of this object (the Finalize method inherits or overrides the child object) at a certain time, and the code within the Finalize method may turn the object into a reachable state, otherwise the object will be turned into an untouchable state.

3. Untouchable state: The GC thread can reclaim the object's memory only if the object is in an unreachable state.

In order to properly release objects, the GC must monitor the running state of each object, including the object's request, reference, reference, assignment, and so on, and the GC needs to monitor, so the 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, and when is it to be executed? Because different JVM implementations may use different algorithms to manage GC, at any time, developers cannot anticipate the timing of the GC thread's actions, including detecting object state, releasing object memory, and calling the object's Finalize method. Although GC threads can be alerted by the System.GC () and RUNTIME.GC () functions for garbage collection operations as soon as possible, this does not guarantee that the GC thread will immediately take the appropriate recycling action.

Memory leaks

Memory leak means that the program fails to release memory that is no longer in use due to faulty design, resulting in waste of resources. The GC automatically cleans up memory occupied by objects that are missing references. However, a memory leak occurs when some objects are always referenced because of programming errors.

Like the following example. Using an array to implement a stack, there are two operations into 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 stack public void push (Object o) {capacity ();
  elements[size++] = o;
    }//out 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 < 100;
    i++) {System.out.println (Stack.pop (). toString ());
 }
  }
}

This program is available to support commonly used stack and stack operations. However, there is one problem that has not been handled well, that is, when the stack is out of operation, there is no reference to the stack element in the array, which causes the program to keep a reference to the object (this object is referenced by an array), and the GC always considers the object to be accessible and even less free of its memory. This is a typical case of memory leaks. For this, the modified code is:

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

The above in-depth understanding of the Java garbage collection mechanism and memory leak is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.