Home Java javaTutorial Detailed explanation of the marking of recycled objects in Java and the secondary marking process of objects

Detailed explanation of the marking of recycled objects in Java and the secondary marking process of objects

Oct 11, 2017 am 10:12 AM
java mark

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();
}
}
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles