How does Java garbage collection work ?, Java garbage collection

Source: Internet
Author: User

How does Java garbage collection work ?, Java garbage collection

This tutorial aims to understand the basic Java garbage collection and how it works. This is the second part of the garbage collection tutorial series. I hope you have read the first part: Java garbage collection introduction.

Java garbage collection is an automated process used to manage the runtime memory used by programs. Through this automated process, JVM removes the overhead for programmers to allocate and release memory resources in the program.

Start Java garbage collection

As an automatic process, programmers do not need to start the garbage collection process explicitly in the code.System.gc()AndRuntime.gc()It is used to request JVM to start garbage collection.

Although this request mechanism provides programmers with an opportunity to start the GC process, the JVM is responsible for the startup. JVM can reject this request, so it is not guaranteed that all these calls will be garbage collection. The JVM determines the start time and whether the Eden zone in the heap memory is available. JVM leaves this option to Java standard implementation. Different implementations use different algorithms.

Undoubtedly, we know that the garbage collection process cannot be enforced. I just found a callSystem.gc()Meaningful scenarios. This article describes how to call System. gc.

Java garbage collection process

Garbage collection is a process of recycling useless memory space and making it available to future instances.

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

Note:If you cannot understand these terms, I suggest you read this garbage collection introduction. This tutorial details the memory model, JVM architecture, and these terms.

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

Shouldn't Eden and S0 both survive and be moved to S1. why is it first moved to S0 and then from S0 to S1 ?)

The dead instance (no longer referenced) is marked as garbage collection. Depending on the garbage collector (which has four common garbage collectors, which will be introduced in the next tutorial), or the marked instances will be removed from the memory constantly, either the recycle process is completed in a separate process.

Old:Old or tenured generation is the second logical zone in heap memory. When the Garbage Collector executes the Minor GC cycle, the surviving instances in the S1 region vor region will be promoted to the old age, and the unreferenced objects will be marked as recycled.

GC in earlier years (Major GC ):Compared with Java garbage collection, the old stage is the final stage of the Instance lifecycle. The garbage collection process in the old age of Major GC scanning. If instances are no longer referenced, they will be marked as recycled; otherwise, they will remain in the old age.

Memory fragmentation:Once an instance is deleted from the heap memory, its location becomes null and can be used for future instance allocation. These empty spaces will make the entire memory area fragmented. Fragment is required for quick instance allocation. Based on the different options of the garbage collector, the recycled memory area is either constantly organized or completed in a separate GC process.

End of the garbage collection instance

Before you release an instance and recycle memory space, the Java Garbage Collector callsfinalize()The instance has the opportunity to release its resources. Although it can be guaranteedfinalize()It is called before memory space is recycled, but there is no specified order or 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 usefinalize()Method To Recycle resources.

  • Any exceptions that are not caught during the finalize process are automatically ignored, and the finalize process of the instance is canceled.
  • The JVM specification does not discuss the garbage collection mechanism for weak references, and there are no clear requirements. The specific implementation is determined by the implementer.
  • Garbage collection is completed by a daemon thread.
When does the object meet the garbage collection condition?
  • All instances are not accessed by active threads.
  • A circular reference instance that is not accessed by any other instance.

Java has different reference types. Determining whether an instance meets the garbage collection condition depends on its reference type.

Reference Type Garbage Collection
Strong Reference) Garbage Collection
Soft Reference) Garbage collection may be executed, but it will be the final choice
Weak Reference) Garbage Collection
Phantom Reference) Garbage Collection

As an optimization technology in the compilation process, the Java compiler can assignnullValue to 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 above class,lionThe object has never been used after the row is instantiated. Therefore, the Java compiler can be used as an optimization method to assign values after instantiating rows.lion = null. Therefore, even before SOP output, the finalize function can print'Rest in Peace!'. We cannot prove that this will happen, because it depends on the JVM implementation method and the memory used in runtime. However, we can also learn that, if the compiler sees that the instance will no longer be referenced in the future, it can select and release the instance Space Early.

  • There is a better example of when the object meets garbage collection. All attributes of the instance can be stored in registers, and the registers will be accessed and 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 conforming to garbage collection. This is a classic example, isn't it?
  • When the value is null, this is a simple example of garbage collection. Of course, complex situations can be like the above. This is the choice made by the JVM implementer. The goal is to keep as little memory as possible, speed up response, and increase throughput. To achieve this goal, the JVM implementers can choose a better solution or algorithm to reclaim memory space during garbage collection.
  • Whenfinalize()When the method is called, JVM releases all synchronization locks on the thread.
Sample GC Scope Program
Class GCScope {GCScope t; static int I = 1; public static void main (String args []) {gcs1_t1 = new GCScope (); gcs1_t2 = new GCScope (); gcs1_t3 = new gcs1_(); // No Object Is Eligible for GCt1.t = t2; // No Object Is eligvisible for GCt2.t = t3; // No Object Is Eligible for GCt3.t = t1; // No Object Is Eligible for GCt1 = null; // No Object Is Eligible for GC (t3.t still has a reference to t1) t2 = Null; // No Object Is Eligible for GC (t3.t. t still has a reference to t2) t3 = null; // All the 3 Object Is Eligible for GC (None of them have a reference. // only the variable t of the objects are referring each other in a // rounded fashion forming the Island of objects with out any external/reference)} protected void finalize () {System. out. println ("Garbage collected from object" + I); I ++;} class GC Scope {GCScope t; static int I = 1; public static void main (String args []) {gcs1_t1 = new gcs1_(); gcs1_t2 = new gcs1 (); gcs1_t3 = new gcs1_(); // no object conforms to GCt1.t = t2; // no object conforms to GCt2.t = t3; // no object conforms 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 comply with GC (none of them have references. // Only the variable t of each object points to each other, // forms a Circular 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

GC does not guarantee the security of the memory overflow problem. Careless code writing will causeOutOfMemoryError.

import java.util.LinkedList;import java.util.List;public class GC {public static void main(String[] main) {List l = new LinkedList();// Enter infinite loop which will add a String to the list: l on each// {l.add(new String("Hello, World"));} while (true);}}


Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceat java.util.LinkedList.linkLast( java.util.LinkedList.add(

Next is the third part of the garbage collection series. We will see different common Java garbage collectors.

Original article: javapapers Translation: Yun

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: 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.