How does Java garbage collection work?

Source: Internet
Author: User

Directory
    1. Introduction to Garbage collection
    2. How does garbage collection work?
    3. Categories of garbage collection
    4. Garbage collection Monitoring and analysis

This tutorial is to understand basic Java garbage collection and how it works. This is the second part of the garbage Collection Tutorial series. I hope you've read the first part: Introduction to Java garbage collection.

Java garbage Collection is an automated process for managing the run-time memory used by your program. With this automated process, the JVM relieves the programmer of the overhead of allocating and freeing memory resources in the program.

Start Java garbage Collection

As an automated process, programmers do not need to display the garbage collection process in the code. System.gc()and Runtime.gc() used to request that the JVM initiate garbage collection.

Although this request mechanism provides the programmer with an opportunity to start the GC process, it is the JVM's responsibility to start. The JVM can reject this request, so there is no guarantee that these calls will be garbage collected. The choice of startup timing is determined by the JVM and depends on whether the Eden Zone is available in heap memory. The JVM leaves this selection to the Java specification implementation, and the algorithms used in different implementations vary.

Needless to tell, we know that the garbage collection process is not enforceable. I just found a call System.gc() to make a meaningful scene. Use this article to learn about the extreme situations that are appropriate for calling System.GC ().

Java garbage Collection process

Garbage collection is a process that reclaims useless memory space and makes it available to future instances.

Eden Zone: When an instance is created, it is first stored in the heap memory of the young generation's Eden area.

Note: If you don't understand these words, I suggest you read this garbage collection introduction , which describes the memory model, the JVM architecture, and these terms in detail.

Survivor Area (S0 and S1): as part of the young generation GC (Minor GC) cycle, the surviving objects (still referenced) are moved from the Eden area to Survivor in the S0 area. Similarly, the garbage collector scans the S0 and then moves the surviving instance to S1.

S0: Should this not be the case for Eden and the survival of the S1, why move to S0 and then move from S0 to S1? )

Instances of death (no longer referenced) are marked as garbage collection. Depending on the garbage collector (four commonly used garbage collector, which will be described in the next tutorial), either the flagged instance will be removed from memory continuously, or the recycle process will be completed in a separate process.

old age: old or tenured generation is the second logical area in heap memory. When the garbage collector performs the Minor GC cycle, the surviving instances in the S1 Survivor Zone are promoted to the old age, and unreferenced objects are marked for recycling.

old age GC (Major GC): The old age is the last phase of the instance life cycle relative to the Java garbage collection process. Major GC scans the garbage collection process in the old years. If instances are no longer referenced, they will be marked as recycled or they will remain in the old age.

Memory Fragmentation: Once an instance is removed from the heap memory, its location becomes empty and can be used for future instance allocations. These vacated spaces will fragment the entire area of memory. For quick allocation of instances, defragmentation is required. Based on the different choices of the garbage collector, the reclaimed memory area is either kept organized or completed in a separate GC process.

End of instance in garbage collection

Before releasing an instance and reclaiming memory space, the Java garbage collector invokes the instance's respective  finalize ()   method so that the instance has the opportunity to release the resources it holds. Although can guarantee  finalize ()   will be called before the memory space is reclaimed, but there is no specified order and time. The order between multiple instances is unpredictable and may even occur in parallel. The program should not pre-adjust the order between instances and use  finalize ()   method reclaims the resource.

    • Any exception that is not caught in the finalize process is automatically ignored, and then the finalize procedure for that instance is canceled.
    • The garbage collection mechanism for weak references is not discussed in the JVM specification and is not explicitly required. Specific implementations are determined by the implementation party.
    • Garbage collection is done by a daemon thread.
When does the object meet the garbage collection criteria?
    • All instances have no active thread access.
    • A circular reference instance that is not accessed by any other instance.

There are different reference types in Java. The criteria that determine whether an instance conforms to garbage collection depends on its reference type.

reference type garbage collection
Strong references (strong Reference) Not eligible for garbage collection
Soft references (Soft Reference) Garbage collection may be performed, but will be used as a final choice
Weak references (Weak Reference) Compliant with garbage collection
Virtual reference (Phantom Reference) Compliant with garbage collection

As an optimization technique during the compilation process, the Java compiler can choose to assign values to the instance to null mark 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 class above, lion   objects have never been used after instantiating a row. Therefore, as an optimization measure, the Java compiler can assign a value lion = null . Therefore, even before the SOP output, the Finalize function can print out the   ' Rest in peace! ' . We cannot prove that this is OK because it relies on the way the JVM is implemented and the memory that is used by the runtime. However, we can also learn one thing: If the compiler sees that the instance will not be referenced again in the future, it can select and release the instance space early.

    • There is a better example of when an object is eligible for garbage collection. All of the properties of the instance are stored in registers, and then the registers are accessed and the contents are read. Without exception, these values will be written back to the instance. Although these values can be used in the future, this instance can still be marked as garbage collected. This is a classic example, isn't it?
    • When assigned null, this is a simple example of a garbage collection. Of course, the complex situation can be like the above points. This is the choice made by the JVM's implementation. The goal is to leave as little memory footprint as possible, speed up response, and improve throughput. To achieve this goal, the JVM's implementation can choose a better scheme or algorithm to reclaim memory space during garbage collection.
    • When the finalize() method is called, the JVM frees all the synchronization locks on that thread.
GC Scope Sample Program
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 is eligible for gct1.t = T2; No Object is eligible for gct2.t = T3; No Object is eligible for gct3.t = T1;  No object is eligible for GCT1 = null;//No object was eligible for GC (t3.t still have a reference to T1) t2 = null;//No Object is eligible for GC (T3.T.T still have a reference to t2) t3 = null;//All the 3 object was eligible for GC (None of T Hem has a reference.//only the variable t of the objects is referring each other in a//rounded fashion forming the ISL And of objects with off any external//reference)}protected void Finalize () {System.out.println ("garbage collected from OB Ject "+ i); i++;} 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 conforms to gct1.t = T2; No objects conform to gct2.t = T3;No objects conform to gct3.t = T1; No object conforms to GCT1 = null;//No object conforms to GC (t3.t still has a reference to T1) t2 = null;//No object conforms to GC (T3.T.T still has a reference to t2) t3 = null;//All three objects are eligible for GC (none of them has a reference.) Only the variable t of each object points to each other, and/or forms a ring-shaped island composed of objects without any external references. )}protected void Finalize () {System.out.println ("Garbage collected from Object" + i); i++;}
Sample program for GC OutOfMemoryError

The GC does not guarantee the security of the memory overflow problem, which is caused by the careless writing of the Code OutOfMemoryError .

Import Java.util.linkedlist;import Java.util.list;public class GC {public static void main (string[] main) {List L = new Li Nkedlist ();//Enter infinite loop which would add a String to the list:l on each//iteration.do {l.add (New String ("Hello, World ")); while (true);}}

Output:

Exception in thread "main" Java.lang.OutOfMemoryError:Java heap spaceat java.util.LinkedList.linkLast (Linkedlist.java : 142) at Java.util.LinkedList.add (linkedlist.java:338) at Com.javapapers.java.GCScope.main (gcscope.java:12)

Next comes the third part of the garbage collection tutorial, and we'll see the different Java garbage collectors that are commonly used.

original link: Javapapers translation: Importnew.com - Woo Jun
translation Links: Http://www.importnew.com/13493.html

How does Java garbage collection work?

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.