search
HomeWeb Front-endJS TutorialA brief analysis of the heap and garbage collection mechanism

A brief analysis of the heap and garbage collection mechanism

Jul 03, 2020 am 09:20 AM
Garbage collection mechanism

In this article we mainly focus on these issues:: After the Java program is executed, when will the objects in the heap be recycled? How to recycle?

The heap is also called the "GC heap." Since collectors now basically use generational collection algorithms, the Java heap can also be subdivided into: new generation and old generation. The ratio is 1:2; to be more detailed, the new generation is divided into Eden area and Survivor area, and the ratio is 8:1. The following figure shows the structure of the heap:

##The allocation of memory for objects in the heap is strictly regulated , the strategy is:

  • Objects allocate memory in the new generation Eden area first;

  • ## Large objects enter the old generation directly, mainly long strings and arrays, which require a large amount of continuous memory space;

  • Long-term surviving objects enter the old generation. When the memory in the Eden area is insufficient, the JVM initiates a MinorGC, and the age of the object is increased by one. The default object age reaches 15 and enters the old age;

  • Dynamic age determination. The sum of the sizes of all objects of the same age is greater than half of the Survivor space. Objects greater than or equal to this age enter the old generation

The new generation GC refers to the Minor GC. Garbage collection in the new generation is frequent and fast. Old generation GC (Major GC/Full GC) performs garbage collection in the old generation, usually accompanied by at least one minor gc. Slow. Full GC will be triggered in the following situations:

    Insufficient space in the old generation;
  1. Insufficient space in the method area;
  2. Call System.gc(), it is recommended that the JVM perform full gc;

  3. Long-term surviving objects are transferred to the old generation , insufficient space;

  4. There is not enough contiguous space allocated to large objects;

  5. There are too many objects that survive garbage collection in the new generation, and S1 cannot fit them in. The guaranteed space in the old generation is insufficient. The guaranteed space refers to whether the maximum available continuous space in the old generation is greater than the total space of all objects in the new generation.

Almost all objects are placed in the heap, so how do we know whether these objects are still useful? JVM provides two methods to determine:

  • ##Reference counting method: The object adds a reference counter. Every time it is referenced, the counter value increases by one. When the reference becomes invalid, the counter value decreases by one. When the number of references is 0, it means that the object is not alive. The reference counting method cannot solve the circular reference problem. There are detailed examples in Teacher Zhou Zhipeng's book, which is relatively easy to understand.

  • #reachability analysis method : Taking the "GC Roots" object as the starting point, just like the root node of a tree, search downwards. The path traveled by the search is called a reference chain. If there is no reference chain from an object to the starting point of GC Roots, then this The object is unreachable and needs to be recycled. GC Roots refers to objects referenced by the virtual machine stack, objects referenced by the local method stack, objects referenced by static properties in the method area, and objects referenced by constants in the method area.

## References were mentioned above. The survival of objects is related to references. Reference types are divided into strong references, soft references, weak references, and virtual references.

Strong reference, new object, the garbage collector will never recycle it;

  • Soft reference, the memory of these objects will be recycled before OMM occurs in the system;

  • Weak reference, as soon as the garbage collector finds it when it is working, it will be recycled immediately ;

  • Virtual reference is useless and may be recycled at any time.

In fact, unreachable objects determined by the reachability analysis method will not be recycled immediately. The object needs to be marked twice before it is actually recycled. . The first marking is to determine that the object is unreachable, and then a filter is performed. The filter condition is whether it is necessary to execute the finalize() method of this object. If the finalize() method is not overridden or the finalize() method has been called by the virtual machine, the finalize() method will only be called once by the system. In both cases, there is "no need to execute". If necessary, this object will be placed in the F-Quene queue, a low-priority automatically created by the virtual machine. FinalizerThe thread executes the finalize() method. During this period, the GC will mark the object in F-Quene for a second small scale. If the object is still not referenced, it will be recycled. Objects that are not filtered are not necessarily recycled.

#We already know what the object is Time has been recycled, so how to recycle it? Introducing the four most commonly used garbage collection algorithms:

  • Mark-clear: mark the objects that need to be cleared first, and then collect them uniformly ---- not efficient, will Generates a large number of discontinuous fragments;

  • Copy algorithm: Divide the memory into blocks, use only one block at a time, and copy the surviving objects to another after use. On one piece;

  • Marking and sorting: mark the surviving objects first, then move all surviving objects to one end, and directly clean up the memory outside the end boundary;

  • Generational algorithm, the heap is divided into the new generation and the old generation. A large number of objects will die every time the new generation is collected, so choose the copy algorithm. The survival rate of the old generation is relatively high, and there is no extra space for allocation guarantee, so choose the mark clearing or mark sorting algorithm.

The garbage collection algorithm is an idea of ​​memory recycling, and the specific implementation is a garbage collector. A brief introduction to commonly used garbage collectors:

  • serial serial collector. Single thread, other work must be suspended during garbage collection. Copying for new students, labeling for old people. Simple and efficient;

  • ParNew collector. The multi-threaded version of serial;

  • Parallel Scavenge collector, a multi-threaded collector of the replication algorithm. Pay attention to throughput, cpu running code time / total cpu time spent. New generation copy, old mark sorting;

  • Serial Old collector, old generation version;

  • Parallel Old collector, Parallel Scavenge old generation version;

  • CMS collector, focusing on the shortest pause. With a concurrent collector, the garbage collection thread works (basically) simultaneously with the user thread. Mark-and-sweep algorithm

For more details about the garbage collector, you can read Mr. Zhou Zhipeng’s book.

Recommended tutorial: "

JS Tutorial"

The above is the detailed content of A brief analysis of the heap and garbage collection mechanism. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment