search
HomeJavajavaTutorialShare Java garbage collection mechanism learning summary

This article shares the learning summary of Java garbage collection mechanism

Memory leak: Memory leak means that the memory space is not recycled after it is used. Generally speaking, memory leaks in Java are because the life cycle of the memory object exceeds the length of time it exists in the program.

The meaning of garbage collection: solve the memory management issues that need to be considered when programming, and effectively solve the memory leak problem. Make full use of free memory space. Java objects no longer have the concept of scope, only references to objects have scope.

Basic operations: (1) Discover useless objects; (2) Recycle the space occupied by useless objects and release it into space that can be used again by the program.

Recycling time: The specific time when garbage collection occurs is unpredictable. Generally speaking, there are two opportunities:

The programmer calls the GC interface of the JVM, but only informs the system that it wants to perform garbage collection. The specific time is determined by the system;

If a large block of memory is needed when the program is running, it cannot provide enough at this time. If the block is large, the system will call GC for garbage collection.

Recycling algorithm:

Reference counting method

Content: Each object is created When the object instance is assigned to a variable (called a reference counter), the initial value of the variable count is set to 1. When the object is referenced, the count value is increased by 1. When a reference of an object instance exceeds the life cycle or is When set to any other value, the reference counter is decremented by 1. When the reference counter value reaches 0, it can be garbage collected. (Note: This object instance may also refer to other objects, so when the object is recycled, the counters of all objects it refers to will be reduced by 1.)

Evaluation: Can be executed faster, in real time It is more convenient under the system, but it cannot solve the circular reference problem. For example, object a and object b refer to each other, but the values ​​​​of a and b are assigned to null. At this time, the objects referenced by a and b can no longer be accessed, but they refer to each other, causing the value of their reference counter to be non-0. At this point the GC will never reclaim them.

Root search algorithm

Content: Treat all reference relationships in the program as a graph, starting from the root node GC Root object, looking for the node corresponding to the reference, and so on. , all reference nodes form a graph, and the remaining nodes are considered to be unreferenced nodes, that is, useless nodes.

The objects used as GC Root objects in Java are: objects referenced in the Java virtual machine stack, objects referenced by static properties in the method area, objects referenced by constants in the method area, and objects referenced in the local method stack

Mark-Clear Algorithm

Content: Scan from the root collection, mark surviving objects, and then scan unmarked objects for recycling after all scans.

Evaluation: No need to move objects, only non-survival objects are processed. It is more efficient when there are many surviving objects, but it will cause memory fragmentation.

Mark - Organizing Algorithm

Content: Based on Algorithm 3, after recycling useless objects, all surviving objects will be moved to free space to organize free memory .

Evaluation: The overhead cost increases, but the fragmentation problem is solved.

Note: Algorithms 3, 4, and 5 all belong to root search algorithms and are described separately here for ease of understanding.

copying algorithm

Content: Divide the memory into the object area and the free area, scan the object area, and then copy all valid nodes in the object area in sequence to the free area, release the original object area, and then the original object area becomes the free area. Garbage collection is completed during the switching between the object area and the free area.

Evaluation: The recycling of handles is reduced, and fragmentation will not occur, but the program needs to be paused during the switching process.

Generation algorithm

is used to store static files, such as Java classes, methods, etc. The persistent generation has no significant impact on garbage collection. Objects that still survive after N garbage collections in the young generation will be placed in the old generation. Therefore, it can be considered that the old generation stores objects with long life cycles.

The memory is much larger than that of the new generation (probably the ratio is 1:2). When the old generation memory is full, Major GC is triggered, that is, Full GC. The frequency of Full GC is relatively low, and the survival time of old generation objects is relatively long. Survival rate mark is high.

All newly generated objects are first placed in the young generation. The goal of the young generation is to collect objects with short life cycles as quickly as possible.

The new generation memory is divided into one eden area and two survivor (survivor0, survivor1) areas in a ratio of 8:1:1. One Eden area and two Survivor areas (generally speaking). Most objects are generated in the Eden area. When recycling, first copy the surviving objects in the eden area to a survivor0 area, and then clear the eden area. When this survivor0 area is also full, copy the surviving objects in the eden area and survivor0 area to another survivor1 area, and then clear eden and this area. In the survivor0 area, the survivor0 area is empty at this time, and then the survivor0 area and the survivor1 area are exchanged, that is, the survivor1 area is kept empty, and so on.

When the survivor1 area is not enough to store the surviving objects of eden and survivor0, the surviving objects are directly stored in the old generation. If the old generation is also full, a Full GC will be triggered, that is, both the new generation and the old generation will be recycled.

The GC that occurs in the new generation is also called Minor GC. The frequency of Minor GC is relatively high (not necessarily in the Eden area). Triggered only when full)

Content: Based on the different life cycles of different objects, objects are processed in generations (divided into three generations: new generation, old generation, and persistent generation).

New generation:

Old generation:

Persistent generation:

The above is the detailed content of Share Java garbage collection mechanism learning summary. 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
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

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

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools