当前位置:网站首页>Introduction to JVM principle
Introduction to JVM principle
2022-07-27 04:09:00 【xmh-sxh-1314】
One 、 What is? JVM
JVM yes Java Virtual Machine(Java virtual machine ) Abbreviation ,JVM Is a specification for computing equipment , It's an imaginary computer , It is realized by simulating various computer functions on a real computer .
Java One of the most important characteristics of language is that it is platform independent . While using Java Virtual machine is the key to realize this feature . General high-level languages run on different platforms , At least it needs to be compiled into different object code . And introduce Java After the language virtual machine ,Java The language does not need to be recompiled when it runs on different platforms .Java Language use Java Virtual machines block information about specific platforms , bring Java Language compilers only need to be generated in Java Target code running on virtual machine ( Bytecode ), It can run unmodified on multiple platforms .Java When the virtual machine executes bytecode , Interpret bytecode as machine instruction execution on a specific platform . This is it. Java Can “ A compilation , Run anywhere ” Why .
from Java From the logical structure of the platform , We can see from the figure below JVM:
Technology sharing
It can be clearly seen from the above picture Java Each logic module included in the platform , You can also learn that JDK And JRE The difference between , about JVM Its own physical structure , We can have a bird's-eye view from the following figure :
Technology sharing
Two 、JAVA Code compilation and execution process
Java The code is compiled by Java Source compiler to complete , The flow chart is shown below :
Technology sharing
Java Bytecode is executed by JVM Execute the engine to complete , The flow chart is shown below :
Technology sharing
ava The whole process of code compilation and execution includes the following three important mechanisms :
Java Source compilation mechanism
Class loading mechanism
Class execution mechanism
Java Source compilation mechanism
Java Source compilation consists of the following three procedures :
Analyze and input to symbol table
Annotation Processing
Semantic analysis and generation class file
The flow chart is shown below :
Technology sharing
Last generated class The document consists of :
structural information . Include class File format version number and information about the number and size of each part
Metadata . Corresponding to Java Information about declarations and constants in the source code . Containing class / Inherited superclasses / Declaration information of the implemented interface 、 Domain and method declaration information and constant pools
Methods information . Corresponding Java Information corresponding to statements and expressions in source code . Contains bytecode 、 Exception handler table 、 Evaluation stack and local variable area size 、 Type record of evaluation stack 、 Debug symbol information
Class loading mechanism
JVM The class of is loaded through ClassLoader And its subclasses , The hierarchical relationship and loading order of classes can be described in the following figure :
Technology sharing
1)Bootstrap ClassLoader
Responsible for loading $JAVA_HOME in jre/lib/rt.jar All in class, from C++ Realization , No ClassLoader Subclass
2)Extension ClassLoader
Responsible for loading java Some of the extensions in the platform jar package , Include $JAVA_HOME in jre/lib/*.jar or -Djava.ext.dirs Specify... In the directory jar package
3)App ClassLoader
Responsible for recording classpath Specified in the jar Package and directory class
4)Custom ClassLoader
It belongs to the application customized according to its own needs ClassLoader, Such as tomcat、jboss Will be based on j2ee Norms are self actualized ClassLoader During the loading process, it will check whether the class has been loaded , The inspection sequence is bottom-up , from Custom ClassLoader To BootStrap ClassLoader Check layer by layer , Just one classloader Loaded is treated as loaded , Guarantee that only ClassLoader To load a . And the order of loading is top-down , That is, the upper layer will try to load this class layer by layer .
Class execution mechanism
JVM It's based on the stack architecture class Bytecode . After thread creation , Will generate program counters (PC) And the stack (Stack), The program counter stores the offset within the method of the next instruction to be executed , Stack frames are stored in the stack , Every stack frame corresponds to every call of every method , And stack frame is composed of local variable area and operand stack , The local variable area is used to store the local variables and parameters in the method , The stack of operands is used to store intermediate results generated during method execution . The structure of the stack is shown in the figure below :
Technology sharing
3、 ... and 、JVM Memory management and garbage collection
JVM Memory structure
JVM Stack by heap 、 Stack 、 Native Method Stack 、 Method area, etc , The structure diagram is shown below :
Technology sharing
1) Pile up
All through new The memory of the created objects is allocated in the heap , The size of the heap can pass through -Xmx and -Xms To control . The heap is divided into Cenozoic and Paleozoic , The Cenozoic is further divided into Eden and Survivor District , Last Survivor from From Space and To Space form , The structure diagram is shown below :
Technology sharing
The new generation . New objects are all allocated with new generation memory ,Eden When there's not enough space , Will transfer the living object to Survivor in , The size of the new generation can be determined by -Xmn To control , It can also be used. -XX:SurvivorRatio To control Eden and Survivor The proportion of
The old generation . It is used to store objects that survive multiple garbage collections in the new generation
Long lasting belt (Permanent Space) Implementation method area , It mainly stores all loaded class information , Methods information , Constant pool and so on . It can be done by -XX:PermSize and -XX:MaxPermSize To specify the persistent band initialization value and the maximum value .Permanent Space Not equivalent to method area , nothing but Hotspot JVM use Permanent Space To implement the method area , Some virtual machines don't have Permanent Space And using other mechanisms to implement the method area .
Technology sharing
-Xmx: Maximum heap memory , Such as :-Xmx512m
-Xms: Initial heap memory , Such as :-Xms256m
-XX:MaxNewSize: Maximum memory area
-XX:NewSize: Initially, the young area memory . Usually it is Xmx Of 1/3 or 1/4. The new generation = Eden + 2 individual Survivor Space . The actual available space is = Eden + 1 individual Survivor, namely 90%
-XX:MaxPermSize: Maximum persistent tape memory
-XX:PermSize: Initially persistent with memory
-XX:+PrintGCDetails. Print GC Information
-XX:NewRatio The proportion of the new generation to the old generation , Such as –XX:NewRatio=2, Then the Cenozoic takes up the whole heap space 1/3, The old generation occupies 2/3
-XX:SurvivorRatio In the new generation Eden And Survivor The ratio of the . The default value is 8. namely Eden Occupying the space of the new generation 8/10, The other two Survivor Each account 1/10
2) Stack
When each thread executes each method, it will apply for a stack frame in the stack , Each stack frame includes a local variable area and an operand stack , It is used to store temporary variables during this method call 、 Parameters and intermediate results .
-xss: Set the stack size for each thread . JDK1.5+ Stack size per thread is 1M, Generally speaking, if the stack is not very deep , 1M It's absolutely enough .
3) Native Method Stack
Used to support native Method execution , It stores everything native The state of the method invocation
4) Method area
Stored the class information to be loaded 、 Static variables 、final Constant of type 、 Property and method information .JVM With persistent generation (Permanet Generation) To store the method area , It can be done by -XX:PermSize and -XX:MaxPermSize To specify the minimum and maximum values
Garbage collection is divided into... According to the basic collection strategy
Reference count (Reference Counting):
Older recycling algorithms . The principle is that this object has a reference , Add a count , Deleting a reference reduces the count by one . Garbage collection , Only the collection count is 0 The object of . The most fatal problem of this algorithm is that it can't deal with circular references .
Mark - eliminate (Mark-Sweep):
Technology sharing
This algorithm is implemented in two stages . In the first stage, all referenced objects are marked from the reference root node , The second stage traverses the entire heap , Clean up unmarked objects . This algorithm needs to pause the whole application , meanwhile , Memory fragmentation will occur .
Copy (Copying):
Technology sharing
This algorithm divides the memory space into two equal areas , Use only one area at a time . Garbage collection , Traverse the current usage area , Copy the object in use to another area . The algorithm only processes objects in use at a time , So the cost of replication is relatively small , At the same time, after copying the past, the corresponding memory can be reorganized , There will be no “ debris ” problem . Of course , The disadvantages of this algorithm are also obvious , It needs twice the memory space .
Mark - Arrangement (Mark-Compact):
Technology sharing
This algorithm combines “ Mark - eliminate ” and “ Copy ” The advantages of the two algorithms . There are also two stages , The first phase starts from the root node to mark all referenced objects , The second stage traverses the entire heap , The untagged objects will be cleared and the living objects will be “ Compress ” To one of the piles , To discharge in order . This algorithm avoids “ Mark - eliminate ” The fragmentation problem of , It also avoids “ Copy ” The space problem of the algorithm .
JVM Different garbage collection mechanisms are adopted for the new generation and the old generation respectively
A new generation of GC:
The Cenozoic usually survive for a short time , Therefore, based on Copying Algorithm to recycle , So-called Copying The algorithm is to scan out the surviving objects , And copy it into a new, completely unused space , Corresponding to the new generation , Is in the Eden and From Space or To Space Between copy. The new generation uses idle pointers to control GC Trigger , The pointer holds the position of the last allocated object in the Cenozoic interval , When there are new objects to allocate memory , Used to check if there is enough space , Not enough to trigger GC. When objects are allocated consecutively , The object will gradually change from eden To survivor, Finally, to the old generation .
In terms of implementation mechanism JVM Serial port is provided GC(Serial GC)、 Parallel recycling GC(Parallel Scavenge) And parallel GC(ParNew)
1) Serial GC
The whole scanning and copying process is carried out in a single thread way , Applicable to single CPU、 The space of the new generation is small and the requirement of pause time is not very high , yes client Level default GC The way , Can pass -XX:+UseSerialGC To force the assignment
2) Parallel recycling GC
In the whole process of scanning and copying, multi-threaded method is adopted , Apply to more CPU、 For applications requiring short pause time , yes server The default level is GC The way , You can use -XX:+UseParallelGC To force the assignment , use -XX:ParallelGCThreads=4 To specify the number of threads
3) parallel GC
Concurrency with older generations GC In combination with
Old generation GC:
The old generation is different from the new generation , The subjects survived longer , More stable , So mark (Mark) Algorithm to recycle , The so-called mark is to scan out the living objects , Then recycle the unlabeled objects , After recycling, you can either merge the space that you use , Or mark it for the next distribution , In short, it is to reduce the efficiency loss caused by memory fragmentation . In terms of implementation mechanism JVM Serial port is provided GC(Serial MSC)、 parallel GC(parallel MSC) And concurrency GC(CMS), The details of the specific algorithm need to be further studied .
All the above GC Mechanisms need to be used in combination , The specified method is shown in the table below :
Specify the way
The new generation GC The way
The old generation GC The way
-XX:+UseSerialGC
Serial GC
Serial GC
-XX:+UseParallelGC
Parallel recycling GC
parallel GC
-XX:+UseConeMarkSweepGC
parallel GC
Concurrent GC
-XX:+UseParNewGC
parallel GC
Serial GC
-XX:+UseParallelOldGC
Parallel recycling GC
parallel GC
-XX:+ UseConeMarkSweepGC
-XX:+UseParNewGC
Serial GC
Concurrent GC
Unsupported combination
1、-XX:+UseParNewGC -XX:+UseParallelOldGC
2、-XX:+UseParNewGC -XX:+UseSerialGC
边栏推荐
- Day 27 of leetcode
- C how to set different text watermarks for each page of word
- Analyze CAS written by CSDN boss, re-entry lock, unfair lock
- Abstract intelligent extraction [based on Bert technology]
- Leetcode- > dichotomy (III)
- PSINS工具箱中轨迹生成工具详细解析
- A. YES or YES?
- 物联网智能家居项目---智能卧室
- STM32CubeMX学习笔记(41)——ETH接口+LwIP协议栈使用(DHCP)
- 【OBS】circlebuf
猜你喜欢

Specific use of multithreading
![[Android synopsis] kotlin multithreaded programming (I)](/img/04/4349bacbd401868d73a3b05d018b66.png)
[Android synopsis] kotlin multithreaded programming (I)

Subject 3: Jinan Zhangqiu line 6

【愚公系列】2022年7月 Go教学课程 018-分支结构之switch

11.zuul路由网关

Application of one-dimensional array

VR全景人淘金“小心机”(上)

Chapter 4 decision tree and random forest

Framework学习之旅:init 进程启动过程

288 page 180000 word intelligent campus overall design directory
随机推荐
3381. Mobile keyboard (Tsinghua University postgraduate entrance examination machine test question)
链表内指定区间反转
什么是动画效果?什么是过渡效果?
手动从0搭建ABP框架-ABP官方完整解决方案和手动搭建简化解决方案实践
路由策略第一关
Golang jwt跨域鉴权
mysql中case when返回多个字段处理方案
Interview question 16.05 factorial mantissa
阿里云服务器域名加端口网页不能访问问题记录
Application of one-dimensional array
288页18万字智能化校园总体设计 目录
Alibaba cloud server domain name and port web page cannot access the problem record
js实现页面跳转与参数获取加载
酷雷曼VR全景为你铺设创业之路
大家有遇到CDC读MySQL字段不全的情况吗?怎么处理的?
二叉树的坡度
Function pointer and callback function
Day 27 of leetcode
Message queue learning -- Concepts
What is the principle difference between lateinit and lazy in kotlin