Home Java javaTutorial Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

Feb 27, 2019 am 11:21 AM
java

The content of this article is about the analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The process of Java code execution and compilation

Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

Java memory management

java Memory model division

Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

Access positioning of objects

Object obj = new Object();
Copy after login

Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

java object creation and initialization

After the java object is created, it will have its own area in the heap memory, followed by the initialization process of the object. Summary of the initialization sequence of class members: first static, then normal, then construct, first parent class, then child class, and the writing order at the same level

  1. Execute the parent class static variables and static code blocks first, and then execute Subclass static variables and static code blocks

  2. Execute the parent class ordinary variables and code blocks first, and then execute the parent class constructor (static method)

  3. Execute subclass ordinary variables and code blocks first, and then execute subclass constructor (static method)

  4. static method initialization precedes ordinary methods, static initialization is only performed when necessary And only initialized once.

Note: For the constructor of a subclass, regardless of whether the constructor takes parameters or not, by default it will first look for the constructor of the parent class without parameters. If the parent class does not have a constructor without parameters, the subclass must use the supper key to call the parent class's constructor with parameters, otherwise the compilation will not pass.

GC recycling mechanism

The garbage collector in Java can automatically reclaim the memory occupied by useless objects, but it is only responsible for releasing all memory occupied by objects created in Java , the memory space allocated for the object through some method other than creating the object cannot be reclaimed by the garbage collector; and garbage collection itself also has overhead, and the priority of GC is relatively low, so if the JVM does not face memory exhaustion, it will not Resources will be wasted for garbage collection to restore memory. Finally, we will find that as long as the program is not close to running out of storage space, the space occupied by the object will never be released. We can actively start a garbage collector through the code System.gc() (although the JVM will not recycle it immediately). Before releasing the memory space allocated by new, the memory space allocated by other methods will be released through finalize().

Which memory needs to be recycled

Memory in java heap and method area

Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)

When to recycle

  1. Reference counting method

Add a reference counter to the object. Whenever there is a place that references it, the counter plus one. On the other hand, every time a reference becomes invalid, the counter is decremented by one. When the counter is 0, it means that the object is not referenced. For example:
Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)
However, the reference counting method cannot solve the circular references between objects, see the following example
Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)
  1. Reachability Analysis

Set up several root objects (GC Root), each object is a child node. When an object cannot find the root, The object is considered unreachable.
Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction)
There is no path from the root to Object4 and Object5, indicating that these two objects are unreachable from the root and can be recycled. In Java, objects that can be used as GC Roots include: objects referenced in the Java virtual machine stack; objects referenced by static variables in the method area; objects referenced by constants in the method area; objects referenced in the local method stack.

How to recycle

  1. Mark-clearing algorithm

First mark all objects that need to be recycled, and after the marking is completed, all marked objects will be recycled uniformly.
This algorithm has two problems: 1) The marking and clearing process is not efficient. Mainly because the garbage collector needs to traverse all reachable objects from the GC Roots root object and add a mark to these objects to indicate that this object is skipped during cleanup. Then during the cleanup phase, the garbage collector will start from Java. The heap is traversed from beginning to end. If an object is not marked, the object will be cleared. Obviously, the efficiency of traversal is very low; 2) A lot of discontinuous space fragments will be generated, so when a larger object needs to be allocated during the running of the program, it may not be able to find enough memory and have to start a garbage collection in advance. .
  1. Copy algorithm

Divide the memory into two blocks and only use one block at a time. When this block of memory is full, the surviving objects are copied to another block and arranged strictly according to the memory address, and then the used block of memory is recycled uniformly.
The advantage is: it can get continuous memory space
The disadvantage is: half of the memory is wasted
Modern JVM does not divide the memory space according to 1:1, but divides the memory into a larger Eden area and two smaller Survivor areas, Eden and a Survivor area are used each time. When recycling, copy the surviving objects in Eden and Survivor to another Survivor at once, and finally clean up the space of Eden and Survivor. In fact, there is another question here: what if after garbage collection, the space required by the surviving objects is greater than the remaining space of the Survivor? The answer is that it needs to rely on other memory for allocation (here mainly refers to the old generation).
  1. Mark-Complete Algorithm

The process is the same as the Mark-Clear algorithm, except that the unmarked memory area is not cleaned after marking. The second is to move all surviving objects to one end, and then clean up the memory outside the boundary
  1. Generation algorithm

The so-called generation It divides the memory into several blocks according to the life cycle of the object, so that the appropriate garbage collection algorithm can be selected according to the "age" of the object. In Java, objects in memory are divided according to their life span: 1. New generation: short life cycle, such as local variables; 2. Old generation: objects with long life cycle; 3. Permanent generation: rarely recycled, Long life cycle, such as loaded class information.
The new generation and old generation are stored in the heap area, and the permanent generation is stored in the method area. Large objects will directly enter the old generation, such as very long strings or large arrays. Large objects are bad news for JVM memory allocation, because large objects need to find contiguous memory, otherwise GC will be triggered, so short-lived large objects are needed Try to avoid it. Objects that have survived for a long time enter the old generation. Each time the object undergoes a minor gc in the new generation, its age is increased by 1. By default, it will enter the old generation when it reaches 15 years old. During each Minor GC, the virtual machine detects whether the average size promoted to the old generation is greater than the current remaining size of the old generation. If it is smaller, a full GC is performed.
The new generation uses a copy algorithm (because there are fewer surviving objects and too many dead objects. If you use the mark-clear algorithm, you need to traverse the marks, which is obviously less efficient. However, using the copy algorithm can save the surviving objects. Copy fewer objects to the available memory area, so the efficiency is higher) for GC recycling. Because the old generation has a high survival rate, it uses mark clearing or mark sorting algorithm for recycling.

The above is the detailed content of Analysis of Java memory mechanism and GC recycling mechanism (picture and text introduction). 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

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

See all articles