search
HomeJavajavaTutorialDetailed explanation of the marking of recycled objects in Java and the secondary marking process of objects

This article mainly introduces the relevant content of the marking of Java recycling objects and the secondary marking process of objects. The editor thinks it is quite good. I will share it with you here. Friends who need it can refer to it.

1. Marking of objects

1. What is a mark? How to mark?

I believe everyone knows the first question. Marking is to mark some dead objects to facilitate the cleaning of the garbage collector. As for how to mark, there are generally two methods: reference counting and reachability analysis.

Reference counting is relatively simple to implement. It is to add a reference counter to the object. Whenever there is a reference to it, it will be incremented by 1. When the reference is invalid, it will be decremented by 1. When the counter is 0, it will be decremented. Marked for recycling. This kind of judgment is very efficient, but many mainstream virtual machines do not use this method, mainly because it is difficult to solve the problem of circular references between several objects. Although it is not used much, it is still worth learning!


public class Test {
private Object obj;
Public static void main(){
Test t1=new Test();
Test t2=new Test();
t1.obj=t2;
t2.obj=t1;
t1=null;
t2=null;
//如果对象在这行发生gc,那么t1和t2对象是否能被回收
System.gc();
}
}

The basic idea of ​​reachability analysis is: by using some objects called "GC Roots" as the starting point, start searching from these nodes, search Objects that have a direct or indirect reference relationship with the node are combined in the form of a chain to form a "relationship network", also called a reference chain. Finally, the garbage collector collects some objects that are not in this relationship network. As shown in the figure:

The object connected to the GC Roots object is an object that is still alive, and the die obj on the right has nothing to do with GCROOTS, so it will be marked as a recyclable object. Currently, mainstream commercial virtual machines use similar methods. So what objects can be used as "GC Roots"? In Java, there are four types of objects that can be used as reference objects in "GC Roots"

1: Stack frame (noun in Chapter 1). (In the stack)

2: Object referenced by static properties. (In the method area)

3: Object referenced by constant. (In the method area)

4: Object referenced by JNI in the local method stack. (In the local method stack)

2. Secondary recycling of objects

I have said that the object is marked, but it does not mean that it is marked. Will it definitely be recycled? I don’t know if you guys remember that the Object class has a finalize() method. All classes inherit the Object class, so this method is implemented by default.

The working principle of finalize should be like this: once the garbage collector is ready to release the storage space occupied by the object, it first calls finalize(), and only during the next garbage collection process, will it really Reclaim the memory of the object. So if you use finalize(), you can perform some important cleaning or cleaning work during garbage collection.
When is finalize() called?

There are three situations

1. All objects are automatically called when they are Garbage Collection, such as when running System.gc().

2. The program exits The finalize method is called once for each object.

3. Explicitly call the finalize method

The purpose of this method is: before the object is recycled, the object's finalize() method will is called. The recycling here refers to after being marked. The problem lies here. Is there a situation where an object is no longer in the "relationship network" (reference chain) mentioned in the previous chapter, but when After the developer rewrote finalize(), and re-added the object to the "relationship network", that is to say, the object is still useful to us and should not be recycled, but it has been marked. What should we do?

In response to this problem, the virtual machine approach is to mark objects twice, that is, mark objects that are not in the "relationship network" for the first time. For the second time, it is necessary to first determine whether the object has implemented the finalize() method. If it has not been implemented, it will be directly determined that the object is recyclable; if it has been implemented, it will be placed in a queue first, and a low level created by the virtual machine. The priority thread will execute it, and then a second small-scale marking will be performed. This time the marked object will actually be recycled.

Summary: Simply put, the object is marked for the first time, and the object's finalize() method will be executed before the next GC. When executing the finalize() method, it is judged whether the object has implemented the finalize() method. If it is not implemented, it is cleared directly; if it is implemented, the object is placed in a queue to execute the finalize method and marked for the second time.
In java root search algorithm To determine the reachability of objects, unreachable objects do not necessarily have to be cleaned up. There is a probation period at this time. To truly judge that an object is dead, it must go through at least two marking processes: If the object finds that there is no reference chain associated with GC roots after performing a root search, it will be marked for the first time and marked. Once filtered, the filtering condition is whether it is necessary for this object to execute the finalize() method. When the object does not cover the finalize() method, or the finalize() method has been called by the virtual machine, the virtual machine will In all cases, it is regarded as "There is no need to execute ".

That is, when an object overrides the finalize() method, the object is determined to be necessary to execute the finalize() method, then the object is placed in the F-Queue queue, and It will be executed later by a low-priority Finalizer thread automatically created by the virtual machine. The so-called execution here means that the virtual machine starts this method, but does not promise to wait for it to finish running. The reason for this: If an object executes slowly in the finalize() method, or an infinite loop occurs (in extreme cases), it may cause other objects in the F-Queue queue to be permanently waiting, or even cause the entire memory to Recycling system crashes. The finalize() method is the last chance for the object to escape the fate of death. Later, the GC will mark the object in the F-Queue for a second small scale. If the object wants to successfully save itself in finalize()----as long as Just re-associate with anything on the reference chain, then it will be removed from the "soon to be recycled" collection when it is marked for the second time; if the object does not escape at this time, it will be recycled. Code example: Refer to the corresponding chapter of "In-depth Understanding of Java Virtual Machine"

Summary

The above is the detailed content of Detailed explanation of the marking of recycled objects in Java and the secondary marking process of objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

Why is Java considered a platform-independent language?Why is Java considered a platform-independent language?Apr 27, 2025 am 12:03 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

How can graphical user interfaces (GUIs) present challenges for platform independence in Java?How can graphical user interfaces (GUIs) present challenges for platform independence in Java?Apr 27, 2025 am 12:02 AM

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.