当前位置:网站首页>JVM second conversation -- JVM memory model and garbage collection
JVM second conversation -- JVM memory model and garbage collection
2022-07-01 14:44:00 【Procedural ape with hair!】
1.JVM Memory model
1.1 Java Object layout
Alignment filling : To ensure that the size of the object is 8 Integer multiples of bytes , Automatic alignment , Avoid multiple loads
1.2 Heap Heap memory distribution
- First use
jdk/bin/jvisualvm.exe
Tools for , Can also be cmd Input directly in the windowjvisualvm
. Open it later inTools - Plug in installation Visual GC
, Monitor the currently started java service
It can be divided into Metaspace Metadata ( Non heap )、Old District old age 、Eden(Survivor0、Survivor1) The Cenozoic is also referred to as Young District
1.2.1 Old District old age
- Every time GC Recycling , Target age +1, Greater than 15 Those that have not been recycled for the first time are added to the elderly generation
- The object memory size is larger than that of the new generation , Then directly join the elderly generation
1.2.2 Young Cenozoic in the area
Because the life cycle of most objects in the new generation is relatively short , Recycling will lead to Young The area space is discontinuous , The problem of space debris .
Cannot allocate when allocating objects that require multiple memory cells , Will cause GC Recycling leads to and CPU Grab time .
So will Young The area is divided into Eden Area and Survivor District
- Eden Only new objects are stored in the area
- As long as it is recycled, put it in S District ,Eden The area can be relatively continuous , But after recycling again S There will also be space debris problems in the area , It will still cause the object to be stuck
- So we distinguish S0(Survivor From)、S1(Survivor To), Each recovery is transferred to the next area , Always promise S0 perhaps S1 One is empty , This solves the problem of fragmentation
- Eden Area and S0、S1 Is the percentage of 8:1:1
- In case the newly generated object is relatively large ,S0、S1 Not enough memory , Need to borrow memory from the elderly , This is called a guarantee mechanism
Will always guarantee S0 perhaps S1 One is empty
2.JVM Garbage collection
2.1 Young GC
Contains Eden、S District , The smallest GC It's called Minor GC
2.2 Old GC
Major GC, Usually accompanied by Minor GC, amount to Full GC
2.3 Full GC
Young GC+ Old GC (+MateSpace GC)
It can lead to stop the work , Try to reduce as much as possible Full GC The frequency of
Allow a certain range of Young GC
2.4 simulation Heap District OOM
- First prepare the code
List<User> str = new ArrayList<>();
@GetMapping("/while")
public void while1() {
while (true){
str.add(new User());
}
}
- Set up JVM Heap memory size
-Xms40M -Xmx40M
- Heap memory distribution and log screenshot
The above figure shows the garbage collection process : - A newly generated object enters Eden District , Find out Eden Zone out of memory , The trigger Young GC
- Young GC First of all, S1 To recycle , Generation age that has not been recycled +1, Transferred to the S0 perhaps Old District ( Meet the age of generations )
- And then to Eden Area for recycling , Those not recycled are transferred to S0, So as to reserve space for new objects
- After recycling ,Eden District or S0 perhaps Old Insufficient space in the area will lead to OOM
2.5 simulation Metaspace District OOM
Java8 Use Metaspace To replace the permanent generation .Metaspace It's the method area Hotspot In the implementation of , Not in virtual machine memory, but directly using local memory .
stay Java8 in ,Class、Metadata Stored in Metaspace In metadata , Forever (Java8 After being Metaspace replace ) Stored some information :
1. Class information loaded by virtual machine
2. Constant pool
3. Static variables
4. Real time compiled code
To simulate Metaspace Space overflow , You can constantly generate proxy classes and add , It will trigger for so long Metaspace OOM
- java Code
public class MetaspaceTest {
static class User {
String name;
}
public static void main(String[] args) {
int i = 0;
try {
while (true) {
i++;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(User.class);
enhancer.setUseCache(false);
enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> methodProxy.invokeSuper(o, args));
enhancer.create();
}
} catch (Throwable e) {
System.out.println("i=" + i);
e.printStackTrace();
}
}
}
- jvisualvm Tool monitoring and logging
as for Metaspace Why is it not filled , Because in Java8 in Metaspace Not in virtual machine memory, but directly using local memory .
3.JVM Garbage collector
3.1 How to determine the garbage object
- Reference count , There may be a circular reference problem, so that neither object can be recycled
- Accessibility analysis , Confirm one GC Root, Start from it , Check whether an object is reachable , Unreachable objects are garbage objects
3.2 GC Root
- Local variable table in virtual machine stack ( Stack -> From the variables being executed in the method area )
- Method area constants or static Variable , Variables in the local method stack
- Class loader
- Thread
3.3 Recovery algorithm
1. Tag clearing algorithm ( The living object 、 Mark the object 、 Unused space )
- Determined as garbage object during scanning , Mark , The next scan will be recycled
- Both marking and clearing scan the entire heap memory space , More time-consuming , After removal, space debris is discontinuous
2. Tag copy algorithm
- Divide an area , Copy the living objects to the new area after marking , Then empty the whole marked area directly , Equate to s0/1
- Although the space is continuous , But it is also a waste of space
2. Marking algorithm
- Move the living objects during the process of clearing after marking
3.4 Garbage collector
Application of the above algorithm , Apply different recycling algorithms to different generations
The new generation : Tag copy algorithm , Old age : Mark clear 、 Sorting algorithm
3.4.1 Serial GC
-XX:+UseSerialGC
- Single thread garbage collector , More applicable to single core CPU, Less memory space
- Applicable to new and old age
- shortcoming : Will pause the business code thread , Because the memory address in the heap will change , You cannot let threads use objects that no longer exist
3.4.2 Parallerl GC
-XX:+UseParallerlGC
- Multithreading , But it will make the application pause , Applicable to new and old age
3.4.3 Concurrent Mark Sweep(CMS)
-XX:+UseConcMarkSweepGC
- It's using a tag removal algorithm , There is a problem of space debris , Only for the old days
- Garbage collector of emergency class , The user thread and garbage collection thread are running simultaneously , Low pause time
3.4.4 G1 Garbage Collector
-XX:+UseG1GC
- Try to meet the pause time goal set by the user , It solves the problem of space debris very well , High throughput
- Tag collation algorithm used , Applicable to new and old age
3.4.5 Z GC
-XX:+UseZGC
- Very small pause time , But some throughput will be sacrificed
4. JVM Tuning latitude
Determine the most reasonable garbage collection period based on business , There are mainly the following latitudes
- Serial : There is only one garbage collector ,Serial
- parallel : Multiple garbage collectors , The business code thread will pause Parallerl GC, Pay more attention to throughput
- Concurrent : Multiple garbage collectors , Business code runs together ,CMS、G1、ZGC, Pay more attention to the pause time
4.1 Pause time
Response time of service interface , Garbage collector performs garbage collection and Client Time to execute response
4.2 throughput
The number of requests or updates completed in the time period , Run user code time / Total time to run user code and garbage collection
That's all for this chapter .
Last one :JVM First words – JVM Introduction details and runtime data area analysis
Next :JVM Third words – JVM Performance tuning practice and record of high-frequency interview questions
There is a good way to study , There's no end to learning how to make a boat
边栏推荐
- [zero basic IOT pwn] reproduce Netgear wnap320 rce
- Provincial election + noi Part IX game theory
- 首届技术播客月开播在即
- Research Report on the development trend and competitive strategy of the global electromagnetic flowmeter industry
- Yyds dry goods inventory hcie security day13: firewall dual machine hot standby experiment (I) firewall direct deployment, uplink and downlink connection switches
- Fundamentals of C language
- 如何看待国企纷纷卸载微软Office改用金山WPS?
- Rearrangement of overloaded operators
- C learning notes (5) class and inheritance
- 一波三折,终于找到src漏洞挖掘的方法了【建议收藏】
猜你喜欢
JVM performance tuning and practical basic theory part II
互联网医院系统源码 医院小程序源码 智慧医院源码 在线问诊系统源码
[leetcode 324] swing sorting II thinking + sorting
sqlilabs less-8
2022-2-15 learning the imitation Niuke project - Section 3 post details
sqlilabs less10
Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models
关于重载运算符的再整理
That hard-working student failed the college entrance examination... Don't panic! You have another chance to counter attack!
[dynamic programming] p1004 grid access (four-dimensional DP template question)
随机推荐
Today, with the popularity of micro services, how does service mesh exist?
Buuctf reinforcement question ezsql
sqlilabs less9
How to view the state-owned enterprises have unloaded Microsoft office and switched to Kingsoft WPS?
One of the first steps to redis
用对场景,事半功倍!TDengine 的窗口查询功能及使用场景全介绍
What are the requirements for NPDP product manager international certification registration?
Using CMD to repair and recover virus infected files
Research Report on the development trend and competitive strategy of the global facial wrinkle removal and beauty instrument industry
Develop small programs and official account from zero [phase III]
sqlilabs less-11~12
博文推荐 | 深入研究 Pulsar 中的消息分块
SWT / anr problem - how to open binder trace (bindertraces) when sending anr / SWT
tensorflow2-savedmodel convert to tflite
Research Report on the development trend and competitive strategy of the global high temperature label industry
Semiconductor foundation of binary realization principle
JVM performance tuning and practical basic theory part II
Research Report on the development trend and competitive strategy of the global ultrasonic scalpel system industry
What problems should be considered for outdoor LED display?
NPDP能给产品经理带来什么价值?你都知道了吗?