This article will bring you an introduction to the Jvm garbage collector (basics) for java learning. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1: Overview
In this article "Jvm Runtime Data Area" introduces various parts of the Java memory runtime area, including the program counter, virtual machine stack, and local method stack. The three areas survive as the thread survives. Memory allocation and deallocation are deterministic. The memory is naturally recycled as the thread ends, so there is no need to consider garbage collection. The Java heap and method area are different. They are shared by each thread, and memory allocation and recycling are dynamic. Therefore, the garbage collector focuses on this part of memory.
Next we will discuss how the Jvm reclaims this part of memory. The first thing the garbage collector does before recycling is to determine which objects are still alive and which are dead. Two basic recycling algorithms are introduced below.
1.1 Reference counting algorithm
Add a reference counter to the object. Whenever there is a reference to it, the counter will be 1, and when the reference expires, the counter will be -1. As long as the counter is equal to 0, the object cannot be used anymore.
This algorithm is a good choice in most cases, and there are also some famous application cases. But it is not used in the Java virtual machine.
Advantages: Simple implementation and high judgment efficiency.
Disadvantages: It is difficult to solve the problem of circular references between objects. For example, the following example
Object a = new Object(); Object b = new Object(); a=b; b=a; a=b=null; //这样就导致gc无法回收他们。
1.2 Reachability analysis algorithm
uses a series of objects called "GC Roots" as the starting point, and searches downward from these nodes to search for the path. The path passed is called a reference chain. When an object does not use any reference chain to GC Roots, it means that the object is unavailable.
In mainstream implementations of mainstream commercial programming languages (Java, C#, etc.), reachability analysis is used to determine whether an object is alive.
Through the following figure, you can clearly feel the connection between gc root and object display. The objects in the gray area shown are alive, and Object5/6/7 are all recyclable objects
In Java language, the objects that can be used as GC Roots include the following types
Objects referenced in the virtual machine stack (local variable table in the stack frame)
Objects referenced by static variables in the method area
Objects referenced by constants in the method area
Objects referenced by JNI in the local method stack (generally speaking Native methods)
Advantages: More accurate and rigorous, can analyze the mutual reference of cyclic data structures;
Disadvantages: The implementation is more complex and requires Analyzing a large amount of data consumes a lot of time, and the analysis process requires GC pauses (reference relationships cannot change), that is, stopping all Java execution threads (called "Stop The World", which is a key issue of garbage collection).
2: Reference
After jdk1.2, Java has expanded the concept of reference, which is generally divided into four categories: strong reference, soft reference, weak reference, and virtual reference. These four The citation intensity gradually weakens.
Strong references: Refers to references that are common in the code, such as Object obj = new Object(); Only strong references can still exists, the GC will never collect the referenced object.
Soft reference: refers to some objects that are useful but not necessary. It will not be garbage collected until there is not enough memory space (before OutOfMemoryError is thrown). Use the SoftReference class to implement soft references
##Weak reference: Used to describe non-essential objects. Such objects will be recycled when the garbage collector works. Use the WeakReference class to implement weak references.
##Virtual reference: Whether an object has a virtual reference, It will not affect its survival time at all. The only purpose is to receive a system notification when the object is recycled. Use the PhantomRenference class to implement
2.1 Determine an object Life or Death
To declare an object dead, it must be marked at least twice.
1. First markIf the object does not find a reference chain connected to GC Roots after the reachability analysis algorithm, it will be marked for the first time. Mark and filter.
Filter conditions: Determine whether it is necessary for this object to execute the finalize() method. Filtering results: When the object does not cover the finalize() method, or the finalize() method has been executed by the JVM, it is determined to be a recyclable object. If it is necessary for the object to execute the finalize() method, it will be placed in the F-Queue queue. This method will be triggered later in the JVM automatically created, low-priority Finalizer thread (possibly multiple threads); The object is marked twice. 3. finalize() method finalize() is a method of the Object class. The finalize() method of an object will only be automatically called once by the system. You can escape death through the finalize() method. object will not be called again for the second time; Because its execution time is uncertain, and even whether it is executed is uncertain (abnormal exit of the Java program), and the running cost is high, and the calling order of each object cannot be guaranteed (even called in different threads). 3: Recycling method area The garbage collection of the permanent generation is mainly divided into two parts: 3.1 Recycling of discarded constantsRecycling of discarded constants is similar to the recycling of Java heap. Here is an example to illustrate 3.2 Recycling useless classes A class must meet the following three conditions at the same time to be considered useless. All instances of this class have been recycled, that is, there are no instances of modified classes in the Java heap. The ClassLoader that loaded this class has been recycled. The java.lang.Class object corresponding to this class is not referenced anywhere, and the methods of this class cannot be accessed through reflection anywhere The virtual machine can recycle classes that meet these three conditions at the same time, but it is not necessary to recycle them. Whether to recycle classes, the HotSpot virtual machine provides the -Xnoclassgc parameter to control. , If the object is re-associated with any object on the reference chain in the finalize() method, it will be removed from the "About to be recycled" collection when it is marked twice. If the object has not escaped successfully at this time, it can only be recycled.
.
Suppose a string "abc" has entered the constant pool, but there is no string object called abc in the current system. That is to say, there is no reference to the string object pointing to the constant pool. abc constant, and there is no need to reference this literal elsewhere. If memory recycling occurs, then the constant abc will be cleared out of the constant pool. The symbolic references of other classes (interfaces), methods, and fields in the constant pool are similar to this.
Java video tutorial
The above is the detailed content of Java Learning Jvm Garbage Collector (Basics). For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.