search
HomeJavajavaTutorialJava Learning Jvm Garbage Collector (Basics)

Java Learning Jvm Garbage Collector (Basics)

Oct 16, 2018 pm 04:14 PM
javajvmGarbage collector

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 mark

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

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.

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;

Special note: It is not recommended to call finalize() in the program for self-rescue. It is recommended to forget about the existence of this method in Java programs.

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:

Abandoned constants and useless classes

.

3.1 Recycling of discarded constantsRecycling of discarded constants is similar to the recycling of Java heap. Here is an example to illustrate

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.

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.

  1. The ClassLoader that loaded this class has been recycled.

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

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

  4. Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit
Java video tutorial

,

java development graphic tutorial

, bootstrap 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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

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

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

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

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

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]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

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

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.