当前位置:网站首页>Enjoy JVM -- knowledge about GC garbage collection
Enjoy JVM -- knowledge about GC garbage collection
2022-07-19 08:23:00 【Java Nana】
How to judge whether an object is garbage
Reference counting
principle : When an object is created ( Generally in the stacking area ) when , Create a counter at the same time , When the object is referenced , Then the counter adds 1, When the reference expires , Then the counter is reduced 1. When the counter is 0 when , Indicates that this object is garbage
problem : There's a circular reference problem . When A quote B,B quote C,C Quote again A Words , Then this 3 An object will never be judged as garbage
Reachability algorithm
Identify some objects as root objects (GC Roots), Starting from these root objects , Traverse to find the objects with reference to these root objects , Form a reference chain , Objects that are not on these reference chains are judged as garbage .
As shown in the figure below , Two light blue objects are garbage .

The problem is coming. , Which objects can be used as GC Roots?
JVM stack: Objects in the virtual machine stack native method stack: Objects in the local method stack runtime constant pool: Objects in the runtime constant pool static reference in method area: Static variables in the method area
How to recycle garbage
Tag clearing algorithm
According to the reachability algorithm , Mark unreachable objects as garbage and uniformly remove all garbage
advantage : When there are fewer objects to recycle , More efficient
shortcoming : A lot of memory fragmentation
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-0WRAcBA7-1657975798774)(https://upload-images.jianshu.io/upload_images/27867710-e01f5fe07b59dfaa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
Tag copy algorithm
Divide the memory area into two parts , Objects are only allocated in half of the area according to the reachability Algorithm , Mark unreachable objects as garbage and copy all living objects to the other half of the area in order , Clear all current areas
advantage : Solve the problem of large amount of memory fragmentation
shortcoming : Half of the memory area is unavailable , Waste of memory

Marking algorithm
According to the reachability algorithm , Mark unreachable objects as garbage, and clean up and copy all living objects to one end of memory
advantage : No memory fragmentation problem , No memory waste
shortcoming : Low efficiency in the replication process

JVM GC Generational algorithm
as everyone knows ,JVM Heap memory is managed in generations , as follows .GC Different methods will be adopted for different areas GC Algorithm

The younger generation : Store a large number of objects that live and die , Using the label copy algorithm , take eden Area and survivor from Mark the garbage in the area , Then copy all the living objects to survivor to District .
Old age : Store long-lived objects , Using the mark sorting algorithm , Every time GC Copy the living object to one end of memory .
GC The timing of
In short : When there is not enough memory , It will happen GC
Minor GC
opportunity :Eden When the object cannot be stored
Algorithm : Tag copy algorithm
Major GC(Full GC)
opportunity :old When the store cannot store objects
Algorithm : Marking algorithm

Garbage collector
Garbage collectors distinguish between younger and older generations

Serial
Young generation collector using replication algorithm , Single thread garbage collection , The recycling process requires STW(stop the world)
The old collector used together :CMS,Serial Old
advantage : Simple , Efficient , Suitable for use in a single core environment
shortcoming : Can't take advantage of the fact that machines are multi-core now
ParNew
Serial Multithreaded version of , In addition to multithreading garbage collection , The rest are related to Serial Agreement
The old collector used together :CMS,Serial Old
advantage : Using the function of multi-core ( In a single core environment ,Serial It's better than ParNew fast )
shortcoming : The recycling process requires STW, When there is too much to recycle , The pause time will be longer
Parallel Scavenge
Young generation collector using replication algorithm , Multithreading for garbage collection , And ParNew The difference is that it focuses on the throughput of the system
throughput = Time to run user code / ( Time to run user code + GC Time for ) High throughput applications are suitable for tasks executed in the background
This collector has two parameters :
-XX:MaxGCPauseMillis: Set the maximum pause time for garbage collection
-XX:GCTimeRatio: Set the ratio of garbage collection time to total time
Set up -XX:MaxGCPauseMillis Can improve response speed , Set up -XX:GCTimeRatio Can improve throughput , Improve CPU Utilization efficiency of
In addition, the collector has another parameter :-XX:UseAdaptiveSizePolicy, Open it up ,JVM According to the running state of the application , Dynamic setting eden District ,survivor District ,old The ratio between districts , To provide the most appropriate pause time or maximum throughput . Here I would like to recommend an architecture learning exchange circle . Exchange learning guidance pseudo Xin :1253431195( There are a lot of interview questions and answers ) It will share some videos recorded by senior architects : Yes Spring,MyBatis,Netty Source code analysis , High concurrency 、 High performance 、 Distributed 、 Principles of microservice architecture ,JVM performance optimization 、 Distributed architecture and other necessary knowledge systems for Architects . You can also get free learning resources , Now it's been a lot of good
Serial Old
Serial Old age version of collector , Single thread , Using the mark sorting algorithm
Parallel Old
Parallel Scavenge Old age version of collector , Multithreading , Using the mark sorting algorithm
CMS(concurrent mark sweep)
A collector designed to minimize pause time
Initial marker : need STW, Mark all root objects in the old age .GC roots Concurrent marking of objects directly referenced and objects referenced by surviving objects in the younger generation : There is no need to STW, Mark all living objects . Start with the root object found in the previous stage , Carry out accessibility analysis .(JVM Will divide the old age logic into areas of equal size in advance Card, Because the application executes concurrently , Some reference relationships may change ,, If the reference relationship changes , Will be passed card marking Mark the area as dirty (dirty card)) Final marker :STW, Rescan objects , Relabel and clear and reset : There is no need to STW, Remove all trash , Reclaiming memory , Reset CMS The internal data of the algorithm , For the next time GC To prepare for
stay java 9 Start to be enabled in , stay java 14 The deleted
advantage :
To reduce the STW Time for , Improve better response speed
shortcoming :
The biggest problem is that the marker removal algorithm is used for the elderly generation , A large number of memory fragments will be generated CPU Resource sensitive , Because there are many concurrent steps , Take up part of the thread , Reducing throughput cannot handle floating garbage ( Concurrent cleanup , New waste may be generated , And you have to wait until the next time GC Handle )
G1
G1 Logically, there are still young people , The concept of the old age . Implementation , The memory area will be divided into several blocks according to a fixed size , be called region. every last region Can belong to eden District , It can also belong to old District , It can change dynamically . Every time GC with region Recycling for units . adopt **-XX:MaxGCPauseMills** This parameter , Can be set every time STW Maximum pause time .eg. Happen when young gc when ,G1 According to the maximum pause time , Try to calculate the cleanability region The number of , You can not clear all young District region, Conduct GC, Achieve effective control GC The pause time of .
gc The algorithm as a whole is tag sorting , From a single region Technically, it's a marker copy , Will single region Copy the surviving object to an empty region Up .
ZGC
The pause time will not exceed 10ms Support large memory , achieve 4TB
so ZGC Suitable for services with large memory and low latency
Shennandoah
CMS A big problem is that the tag is used - Clear algorithm , Leading to serious fragmentation , Think about why CMS Don't use the tag sorting algorithm ? The reason is CMS Hope to reduce STW Time for , So if you sort out with markers , So when sorting , The reference address of the object will change , At this time, the user thread cannot access , Then we have to STW, The reference address can only be used after switching . This will improve STW, So the mark used to clear .
Empathy G1 When marking copy , There will be STW The process of . and Shennandoah When copying , A reading barrier is used and is called “Brooks Pointers” Forward pointer for , Avoid losing STW The process .
Garbage collector summary
About garbage collector , I'm basically talking about , If you are interested in a collector , Can do in-depth research

Common combinations :

边栏推荐
- How to convert STR in read list to float
- sudo pip install gevent 安装失败的解决办法
- 812. Maximum triangle area
- LeetCode 每日一题 2021/7/11-2021/7/17
- Unity custom sky ball model to prevent it from being cropped
- TextView文字上下移动
- 关于快慢指针的理解
- Interview question: outer margin folding problem (bug of block level elements in ordinary document flow)
- 5.1 vulnérabilités et précautions en matière de sécurité
- Visual studio production environment configuration scheme: slowcheetah
猜你喜欢

美联储降息,为何长期利好数字货币市场? 2020-03-05

STM32F103C8T6硬件IIC控制4针0.96寸OLED显示屏

The core problem of concurrent programming

Gateway新一代网关

Application of SCA on devsecops platform

写代码遇到Qt相关问题

Unity: WebGL发布后在浏览器上运行时窗口大小自适应

Real case: how to check the soaring usage of CPU after the system goes online?

ansible自动化运维详解(四)ansible中playbook的编写使用、执行命令及实例演示

真实案例:系统上线后Cpu使用率飙升如何排查?
随机推荐
TextView文字上下移动
From the casino logic, analyze the investment value of platform currency 2020-03-03
[C# Console]-C# 控制台类
C # read and write txt files
sudo pip install gevent 安装失败的解决办法
Great summary! Finally, someone explained all kinds of SQL join connections clearly
在VSCode中设置settings.json
[kernel] character device that drives development and learning
Openpyxl copy sheet pages across workbooks
Deep learning 7 deep feedforward network 2
【Kernel】驱动开发学习之字符设备
Filesourcestrategy, datasourcestrategy and datasourcev2strategy in spark
WPF 三维应用搭建(基础)
Can seaport and erc-4907 become new ways to release NFT liquidity| Tokenview
手把手实践一个DAPP,通往Web3.0之路!
Redis cache avalanche, penetration, breakdown
Eureka基础知识
[C# 类和对象]-C# 中的方法以及类和对象编程
The core problem of concurrent programming
Strategic model of behavioral model