Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the garbage collection mechanism of Java

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to understand the Java garbage collection mechanism". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand the Java garbage collection mechanism".

Java garbage collection is an automatically running process that manages the memory used by the program when it runs. Automating the JVM of GC frees programmers from the onerous task of requesting and freeing memory.

Java garbage collection GC initialization

As an automated process, programmers do not need to initialize GC actively in their code. Java provides two hook, System.gc () and Runtime.gc (), to request JVM to call the GC process.

Although the system mechanism is required to give programmers the opportunity to call GC, it is actually up to JVM to decide. JVM can choose to reject requests to start GC, so there is no guarantee that these requests will actually invoke garbage collection. This is a decision made by JVM based on the usage of the Eden area of the memory heap space. The JVM specification leaves this choice to the specific implementation of each JVM, so how JVM actually chooses depends on the implementation of different JVM (but keep in mind that you cannot rely on calls to these two methods, which are not guaranteed to be executed).

There is no doubt that we know that the garbage collection process cannot be enforced. But I just found a scenario where calling System.gc () does make sense. Take a look at this article and you will understand this particular scenario where the System.gc () call is available.

Java garbage collection process

Garbage collection is a process of reclaiming memory space that is no longer used and turning it into a process that can be used by future instances.

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

Note: if you do not quite understand these terms, it is recommended that you take a look at the article introducing the memory model, JVM architecture, and a detailed explanation of these terms: garbage-collection-introduction-tutorial

Survivor Space (S0 and S1): as part of the minor recycling cycle, living objects (and references to it) are moved from the eden zone to survivor space S0. Similarly, the garbage collector scans S0 and moves the living instance to S1.

Useless objects (no reference points) are marked and recycled. The garbage collector (there are four available garbage collectors, which will be described in the next article) determines whether these marked instances are removed from memory during scanning or executed in a separate migration process.

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

Major GC: a stage in the life cycle of an instance during Java garbage collection. Major GC scans heap memory that is part of Old Generation during garbage collection. If instances are not associated with any references, they will be marked and cleared; if they are still referenced, they will remain in the old generation.

Memory

Fragmentation: once the instances are removed from the heap memory, their original locations will be free for later allocation of instances. Obviously, this free space can easily be fragmented in memory space. In order to allocate instance addresses more quickly, memory needs to be de-fragmented. Depending on the strategy of the garbage collector, the reclaimed memory will be compressed and consolidated at the same time as the recycling process or in a separate process of GC.

Object destruction during garbage collection-Finalization

Just before removing an object and reclaiming its memory space, the Java garbage collector will call the finalize () method of each instance, giving the instance object a chance to release its occupied resources. Although the finalize () method is guaranteed to be executed before memory space is reclaimed, there is no guarantee about the specific execution time and order. The order of finalize () execution between multiple instances cannot be predicted in advance, and it is even possible that they are executed in parallel. The program should not presuppose that the instance executes the method of finalize (), nor should it use the finalize () method to recycle resources.

Any exception thrown during finalize is ignored by default, and the destruction of the object is canceled.

The JVM specification does not discuss garbage collection for weak references, which is explicitly stated. The details are left to the implementer to decide.

Garbage collection is performed by the daemon

When does an object become available for garbage collection?

All threads that cannot be alive reach the instance

There are many different reference types in the circular reference object Java that cannot be reached by other objects. The recyclability of an instance depends on its reference type.

The Java compiler has an optimization mechanism during compilation. The compiler can 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 other than the initialization line. So as an optimization method, the Java compiler can assign lion = null immediately after initializing that line. In this way, finlizer may print the results before the SOP of the Main method.

Rest in Peace! Main is completed.

But the order of the results is uncertain, depending on the implementation of JVM and the memory usage of the runtime. One thing we can know from this is that the compiler can choose to release instance memory in advance when it is no longer referenced in the program after it finds an instance.

Here is a better example of when an example becomes recyclable. All the properties of the instance can be stored in a register and these property values can be read from the register and will not be written back to the instance object in any case in the future. In this way, although the instance is still used in the future, the instance object can still be marked as recyclable.

When it can be garbage collected can be as simple as assuming that the assignment to null can be as complex as mentioned in the above point. The implementers of JVM will make some trade-offs. The goal is to leave the least trace, improve response time and increase throughput. In order to achieve these goals, JVM implementers can choose a better mode or algorithm to reclaim memory in garbage collection.

When finalize () is called, JVM releases all synchronization 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 is t 1.t = T2 that can be GC / / none of the objects can be handled by GC's t 2.t = T3 null / no object can be handled by GC's t 3. T = t 1, no object can be GC, no object can be GC, t 3.t has a reference to T1 = null. / / No object can be GC, and t3.t.t has a reference to T2 T3 = null / / all three objects can be GC (none of them are referenced) / / only the variables t of each object circularly refer to each other to form an isolated reference ring, without external references} protected void finalize () {System.out.println ("Garbage collected from boject" + I); iTunes;}}

Example Program for GC OutOfMemoryError

Garbage collection mechanism does not guarantee the security of memory overflow, in fact, memory overflow will cause the program to crash and throw OutOfMemoryError. Import java.util.LinkedList

Import java.util.List; public class GC {public static void main (String [] args []) {List l = new LinkedList (); / / enter the internal * loop to add elements do {l.add ("Hello, World!");} while (true);}} directly to the linked list

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 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) Thank you for your reading. This is the content of "how to understand Java garbage Collection Mechanism". After the study of this article I believe you have a deeper understanding of how to understand the Java garbage collection mechanism, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report