Java Virtual Machine (iii) garbage tagging algorithms and the life cycle of Java objects

Source: Internet
Author: User

Related articles
Java Virtual Machine Series

Preface

In this section we will briefly introduce the garbage collector, and learn the algorithm of garbage tagging: reference counting algorithm and Root search algorithm, in order to better understand the root search algorithm, the end of the article describes the Java object in the virtual machine life cycle.

1. Garbage collector Overview

The garbage collector (garbage Collection), often referred to as a GC. Referring to the GC, many people think it comes with Java, in fact, the GC appears much earlier than Java, it is 1960 born in the Lisp of MIT.
GC mainly does two work, one is the partition and allocation of memory, and the other is to recycle garbage. On the memory division and allocation, the current Java Virtual machine memory partition is dependent on the design of GC, for example, GC is now using a generational collection algorithm to recycle garbage, Java heap as the main area of GC management, is subdivided into the new generation and the old age, and then a little more detailed cenozoic can be divided into Eden space, The from survivor space, to survivor space, and so on, is partitioned for faster memory allocation and recycling. Once space is partitioned, the GC can allocate memory space for new objects.
Regarding garbage collection, the object being referenced is a surviving object, and the object that is not referenced is the object of death, which is garbage, and the GC distinguishes between the surviving object and the Dead object, that is, the garbage tag, and recycles the garbage. Let's start by introducing the garbage tagging algorithm.

2. Garbage tagging algorithm

Before garbage recycling, GC to mark out the garbage, then how to mark it, there are two garbage tagging algorithms, respectively, is the reference counting algorithm and root search algorithm, these two algorithms are related to the reference, so before talking about garbage tagging algorithm, we first review the referenced knowledge.

References

After JDK1.2, Java divides references into strong references, soft references, soft references, and virtual references.

    • Strong reference: When we new an object is created a strong reference to the object, if an object has a strong reference, the garbage collector will never recycle it. The Java virtual machine prefers to throw outofmemoryerror exceptions, cause the program to terminate abnormally, and not reclaim objects with strong references to resolve out-of-memory issues.
    • Soft reference: If an object has only soft references, when memory is insufficient, the memory of these objects is reclaimed, and if there is not enough memory after recycling, the OutOfMemoryError exception is thrown. Java provides a SoftReference class to implement soft references.
    • Weak reference: A weak reference has a shorter life cycle than a soft reference, and once the garbage collector discovers an object with only a weak reference, its memory is reclaimed regardless of whether the current memory is sufficient. Java provides a WeakReference class to implement weak references.
    • Virtual Reference: A virtual reference does not determine the life cycle of an object, and if an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references. An object that has only a virtual reference, and receives a system notification when it is reclaimed by the garbage collector, which is the primary function of the virtual reference. Java provides a phantomreference class to implement virtual references.
Reference Counting Algorithm

The basic idea of the reference counting algorithm is that each object has a reference counter, and when the object is referenced somewhere, its reference counter is incremented by 1 and the reference is invalidated by 1. When the value in the reference counter becomes 0, the object cannot be used as garbage.
At present, the mainstream Java Virtual machine does not choose the reference counting algorithm for garbage tagging, the main reason is that the reference counting algorithm does not solve the problem of circular referencing between objects.
For example, in the following code, note 1 and note 2, D1 and D2 reference each other, in addition to these two objects have no other reference, in fact, the two objects are dead, should be recycled as garbage, but because the two objects reference each other, the reference count will not be 0, the garbage collector cannot reclaim them.

Class _2mb_data { PublicObject instance =NULL;Private byte[] data =New byte[2*1024x768*1024x768];//used to account for memory, test garbage collection} Public classREFERENCEGC { Public Static void Main(string[] args) {_2mb_data D1 =New_2mb_data (); _2mb_data D2 =New_2mb_data (); D1.instance = D2;//1d2.instance = D1;//2D1 =NULL; D2 =NULL;    System.GC (); }}

If you use Android Studio, just add the following statement to the VM options in edit configurations to output the verbose GC log:

-XX:+PrintGCDetails

To run the program, the GC logs are:
[GC (System.GC ()) [psyounggen:8028k->832k (76288K)]8028k->840k (251392K), 0.0078334 secs] [times:user=0.06 sys=0.00, real=0.01 secs]
[Full GC (System.GC ()) [psyounggen:832k->0k (76288K)] [paroldgen:8k->603k (175104K)] 840k->603k (251392K), [ metaspace:3015k->3015k (1056768K)], 0.0045844 secs] [times:user=0.00 sys=0.00, real=0.00 secs]
Heap
Psyounggen total 76288K, used 1966K [0x000000076af80000, 0x0000000770480000, 0x00000007c0000000)
Eden Space 65536K, 3% used [0x000000076af80000,0x000000076b16bac0,0x000000076ef80000)
From space 10752K, 0% used [0x000000076ef80000,0x000000076ef80000,0x000000076fa00000)
To space 10752K, 0% used [0x000000076fa00000,0x000000076fa00000,0x0000000770480000)
Paroldgen total 175104K, used 603K [0x00000006c0e00000, 0x00000006cb900000, 0x000000076af80000)
Object Space 175104K, 0% used [0x00000006c0e00000,0x00000006c0e96d10,0x00000006cb900000)
Metaspace used 3046K, capacity 4496K, committed 4864K, reserved 1056768K
Class space used 334K, capacity 388K, committed 512K, reserved 1048576K

Before looking at this GC log, let's take a brief look at the meanings of the following parameters, [GC (System.GC () and [Full GC (SYSTEM.GC () describe the type of pause for this garbage collection, rather than distinguishing the new generation GC from the old GC. [Full GC (System.GC () indicates that this GC occurred STW,STW is the stop the world mechanism, meaning that when the garbage collection algorithm is executed, only the GC thread is running, and the other threads are all paused, waiting for the GC thread to finish before it can run again.
Psyounggen represents the new generation, Paroldgen represents the old age, Metaspace represents the meta space (JDK 8 is used to replace the permanent generation PermGen).
We look at the log of [GC (System.GC ()), Memory changes: 8028k->840k (251392K), 8028K represents the amount of memory before recycling, 840K represents the size of the recovered memory, 251392K represents the total memory size. So you can tell that the memory reclaim size is (8028-840) K. This means that the JDK8 hotspot virtual machine does not use a reference counting algorithm to mark memory, which recycles references to two of the dead objects in the code above.

Root Search Algorithm

The basic idea of this algorithm is to select some objects as GC Roots, and make up a collection of root objects, and then search from these objects as GC Roots as the starting point, and if the target object is connected to the GC Roots, we call the target object to be reached, If the target object is unreachable, the target object is an object that can be reclaimed, as shown in.

From the perspective of seeing, Obj5, Obj6 and OBJ7 are unreachable objects, wherein Obj5 and OBJ6 although each other reference, but because they to the GC roots is unreachable, so they will still be judged as recyclable objects, Such a root search algorithm solves the problem that the reference counting algorithm cannot solve: Dead objects cannot be recycled because they are referenced by each other.
In Java, there are several main objects that can be used as GC roots:

    • The referenced object in the Java stack.
    • The object that is referenced by JNI in the local method stack.
    • The object in the method area that runs the constant pool reference.
    • The object referenced by the static property in the method area.
    • Threads that are running
    • Objects loaded by the boot class loader
    • GC-controlled objects

Another problem is that objects that are flagged as unreachable are immediately reclaimed by the garbage collector? To answer this question, we first need to understand the life cycle of Java objects in a virtual machine.

The life cycle of 3.Java objects in virtual machines

When a Java object is loaded into a virtual machine by the ClassLoader, the Java object has 7 stages in the Java Virtual machine.
1. Creation phase (Created)
The steps to create the phase are:

    • Allocates storage space for an object.
    • Constructs an object.
    • Initializes a static member from a superclass to a subclass.
    • Recursive invocation of a superclass's constructor method.
    • Call the constructor method of the subclass.

2. Application phase (in use)
When an object is created and assigned to a variable, the state switches to the application phase.
Objects at this stage must have at least one strong reference, or explicit use of soft, weak, or virtual references.

3. Invisible Stage (Invisible)
No strong references to the object are found in the program, such as the execution of the program has exceeded the scope of the object. In the invisible phase, the object may still be held by a special strong reference GC roots, such as the object being referenced by JNI in the local method stack or referenced by a running thread.

4. Non-reach stage (unreachable)
No strong reference to the object was found in the program, and the garbage collector found the object unreachable.

5. Collection phase (collected)
The garbage collector has found that the object is unreachable and the garbage collector is ready to reassign the object's memory space. At this point, the method is called if the object overrides the Finalize method.

6. Finalization phase (finalized)
When the object is still in the unreachable state after the finalization method is completed, or the object does not override the Finalize method, the object goes to the end stage and waits for the garbage collector to reclaim the object space.

7. Object Space reallocation Phase (deallocated)
When the garbage collector reclaims or re-allocates the memory space of an object, the object disappears completely.

Well, we've learned about the life cycle of Java objects in virtual machines, and then recall the question I just said: Will objects that are flagged as unreachable be immediately reclaimed by the garbage collector? Obviously not, an object that is marked as unreachable goes into the collection phase, and the Finalize method that overrides the object is executed, and if the Finalize method is not overridden or the Finalize method is not re-associated with an reachable object, it goes into the finalization phase and is eventually recycled.

Resources
"In-depth understanding of Java virtual machines: JVM advanced features and Best practices" second Edition
"Java Virtual machine explaining"
"Hotspot Combat"
Best Practices for performance optimization for Android applications
JVM in-depth notes (3) garbage tagging algorithm
GC roots
Java GC-Monitoring recycle behavior and log analysis
Java: Strong, soft, weak, and virtual references to objects
Stop the world case in JVM GC
The life cycle of a Java object

Welcome to my public number, the first time to get blog update reminders, and more into the system of Android-related original technology dry.
Sweep the two-dimensional code below or long press identification QR code, you can pay attention to.

Java Virtual Machine (iii) garbage-tagging algorithm and Java object life cycle

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.