Java garbage Collection Mechanism II working principle –how java Garbage Collection Works?__java

Source: Internet
Author: User
Tags garbage collection

Reprint: http://youli9056.github.io/blog/java-gc-yuan-li/

This article is not original, translated from the article How Java garbage Collection works? The main purpose of this article is to understand the fundamentals of the Java garbage collection mechanism and how it works. This is the second of a series of articles in the garbage collection mechanism. I hope you've read the first part of the Java garbage collection introduction.

Java garbage Collection is a process that automatically runs the memory used by the management program when it runs. The automated JVM of the GC frees programmers from the heavy operations of application and freeing memory. Java Garbage Collection GC initialization

As an automated process, programmers do not have to actively initialize the GC in code. Java provides two hooks for System.GC () and RUNTIME.GC () to request the JVM to invoke the GC process.

While the system mechanism is required to provide programmers with the opportunity to invoke GC, it is in fact the JVM's responsibility to decide. The JVM can choose to deny the request to start the GC, so it does not guarantee that the requests will actually invoke garbage collection. This is the decision taken by the JVM based on the use of the Eden area in memory heap space. The JVM specification leaves this choice to the specific implementations of the various JVMs, so the actual JVM is chosen depending on the implementation of the different JVMs (but remember that you cannot rely on the invocation of these two methods, which are not guaranteed to be executed).

There is no doubt that we know that the garbage collection process is not enforceable. But I just found a scenario where the call to System.GC () does make sense. Take a look at this article and you will understand that the System.GC () call is available in this particular scenario. Java garbage Collection process

Garbage collection is a process that reclaims memory space that is no longer in use and makes it available for future instances.

Eden Space: When an instance is created, it is initially stored in the Eden area of the young generation of the heap memory space.

Note: If you do not understand these terms, it is recommended that you look at the articles that describe the memory model, JVM architecture, and detailed explanations of these terms: garbage-collection-introduction-tutorial

Survivor Space (S0 and S1): As part of the minor recycling cycle, the surviving object (and the reference point to it) is moved from the Eden area to the Survivor spatial S0. Similarly, the garbage collector scans the S0 and moves the living instance to S1.

Unwanted objects (no reference points) are marked and recycled. The garbage collector (four available garbage collector, which will be covered in the next article) determines whether these flagged instances are moved out of memory during a scan or in a separate migration process.

Old Generation: Age or permanent generation is the second logical part of heap memory. When the garbage collector is doing the minor GC cycle, an instance of the S1 survivor region that is alive is promoted to the old age. Objects that are no longer referenced in the S1 area are marked and cleared.

Major GC: The last stage in the life cycle of an instance during Java garbage collection. The Major GC scans the heap memory belonging to the old generation part during garbage collection. If the instance is not associated with any references, they are marked, cleared, and if they are associated with the reference, they remain in the old generation.

Memory fragmentation: Once the instances have been removed from heap memory, their original locations will be vacated for later assignment instances. Obviously, these free spaces are easily fragmented in memory space. In order to be able to allocate the instance address faster, the memory needs to be fragmented. Depending on the policies of the different garbage collector, the reclaimed memory will compress the integration at the same time as the process of recycling or in the process of separate GC. object Destruction –finalization during garbage collection

Just before removing an object and reclaiming its memory space, the Java garbage collector invokes the Finalize () method of each instance so that the instance object has the opportunity to release the resources it occupies. Although the Finalize () method is guaranteed to be performed before the memory space is reclaimed, there is no guarantee of the specific execution time and order of execution. The Finalize () execution order between multiple instances cannot be predicted in advance, and may even be performed in parallel. The program should not assume that the instance executes the Finalize () method, nor should it use the Finalize () method to reclaim the resource. Any exceptions thrown in the finalize process are ignored by default, and the object's destruction process is canceled. The JVM specification does not discuss garbage collection for weak references, which is explicitly stated. The details are left to the person who implements the decision. Garbage collection is when objects executed by the daemon become garbage-collected. There are many different reference types in Java that cannot be lived by a thread that cannot be reached by a loop reference object that an instance cannot be reached by another object. The recyclable nature of an instance depends on its reference type.

Reference Garbage Collection
Strong Refrence Not to be garbage collected
Soft Reference As a final option, it is possible to be recycled
Weak Reference Can be garbage collected
Phantom Reference Can be garbage collected

During compilation, the Java compiler has an optimization mechanism that allows the compiler to choose to assign null to an instance, thus marking the instance as recyclable.

Class Animal {public
    static void Main (string[] args) {
        Animal lion = new Animal ();
        System.out.println ("Main is completed.");
    }

    protected void Finalize () {
        System.out.println ("Rest in peace!");
    }

In the above class, the instance lion is not used anywhere else except for the initialization of the row. Therefore, as an optimization method, the Java compiler can assign Lion = null immediately after the initialization of that line. This finlizer may print the results before the SOP for the main method.

Rest in Peace.
Main is completed.

But the order of the results is indeterminate, depending on the implementation of the JVM and the memory usage at run time. One thing we can learn from this is that the compiler can choose to release the instance memory in advance when it is no longer referenced in the program after discovering an instance. Here's an example of when to recycle better. All properties of an instance can be stored in registers and can be read from registers, and in no case will the value be written back to the instance object in the future. In this way, although this instance is still used in the future, the instance object can still be marked as recyclable. When you can be garbage collected is simple enough to think that when the assignment is null it can also be complex enough to say the above point. The JVM's implementation will make some trade-offs. The goal is to keep a minimum of traces, increase response time and increase throughput. To achieve these goals, JVM implementations can choose a better pattern or algorithm in garbage collection to reclaim memory. When Finalize () is invoked, the JVM frees all the synchronized blocks of the current thread.

Example Program for GC Scope

Class Gcscope {
    gcscope t;
    static int i = 1;
    public static void Main (String args[]) {
        Gcscope t1 = new Gcscope ();
        Gcscope t2 = new Gcscope ();
        gcscope t3 = new Gcscope ();
        No object can be t1.t = t2;//without any object that can be GC
        t2.t = t3;//No object can be gc
        t3.t = t1;//No object can be GC's

        T1 = null;//No object can be GC, t3.t and T1 reference

        t2 = null;//No object can be GC, T3.T.T also have references to t2 t3
        = null;// All 3 objects can be GC (no one is referenced)
                  ///Only the variable t of each object loops through the reference to form an isolated reference ring without an external reference
    }
    protected void Finalize () {
        System.out.println ("Garbage collected from Boject" + i);
        i++
    }
}

Example Program for GC OutOfMemoryError

Garbage collection mechanism does not guarantee the security of memory overflow, in fact, memory overflow will cause the crash of the program, throw OutOfMemoryError.

Import java.util.LinkedList;
Import java.util.List;

public class GC {public
    static void Main (string[] args[]) {
        List L = new LinkedList ();
        Go into the inner infinite loop and add the element do
        {l.add (
            "Hello, world!") to
    the list continuously;

Output

Exception in thread "main" Java.lang.OutOfMemoryError:Java heap spaces at
    java.util.LinkedList.linkLast ( linkedlist.java:142) at
    Java.util.LinkedList.add (linkedlist.java:338)

At Com.javapapers.java.GCScope.main (gcscope.java:12)

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.