当前位置:网站首页>Detailed learning notes of JVM memory structure (I)
Detailed learning notes of JVM memory structure (I)
2022-07-07 09:09:00 【White butterfly】
This blog records personal learning jvm The process of , If there is a mistake , Please correct me
List of articles
One 、 Program counter
1. Introduction to program counter
A program counter is a small amount of memory , It can be seen as The line number indicator of bytecode executed by the current thread . The bytecode interpreter selects the next bytecode instruction to execute by changing the value of this counter , Branch 、 loop 、 Jump 、 exception handling 、 Thread recovery and other functions need to rely on this counter to complete . To make a long story short , It helps the thread record a jvm The execution address and line number of the instruction , If there is no program counter , that jvm I don't know what instruction to execute next
Besides , In order to recover to the correct execution position after thread switching , Each thread needs to have a separate program counter , Counters between threads do not affect each other , Independent storage , We call this kind of memory area “ Thread private ” Of memory . So the program counter is private to the thread
Decompile the class , Input... At the terminal javap -v Class name .class You can view the binary bytecode file (Java Bytecode file .class)
jvm The number in front of the instruction is the sequence stored in the program technician
2. Program counter function
In short , Program technologists have two functions :
- Read the instructions in turn by changing the program counter , So as to realize the flow control of the code
- In the case of multithreading , The program counter is used to record where the current thread is executing , So when the thread is switched back, it can know where the thread last ran
Be careful : The program counter is the only memory area that does not overflow , Its life cycle is created with the creation of threads , With the end of the thread
Two 、Java Virtual machine stack
1. Introduction to virtual machine stack
Same as the program technician ,Java The virtual stack is also thread-private , His life cycle is the same as threads , Created with the creation of threads , With the death of the thread ;
So what is it ?**Java The virtual stack consists of stack frames ,** The memory required by each method in the process of thread running is called stack frame , The data of method calls needs to be passed through the stack , Each method call will have a corresponding stack frame pushed into the stack , After each method call , There will be a stack frame pop up .
Run the following procedure
public class Main {
public static void main(String[] args) {
method1();
}
private static void method1() {
method2(1, 2);
}
private static int method2(int a, int b) {
int c = a + b;
return c;
}
}
Java Method can be returned in two ways , One is return The statement returns normally , One is to throw an exception . Either way , Will cause the stack frame to pop up . in other words , Stack frames are created with method calls , Destroy as the method ends . Whether the method is completed normally or abnormally, it is regarded as the end of the method .
2. Problem Formulation
1. Does garbage collection involve stack memory ?
Can't . Stack memory is generated by method calls , The stack will pop up after the method call .
2. The larger the stack memory allocation, the better ?
No . Because physical memory is certain , The larger the stack memory , Although it can support more recursive calls , But the fewer threads you can execute .
3. Whether local variables in methods are thread safe ?
- If the variables inside the method do not escape the function of the method, access ( Variables are local variables ), It's thread safe
- If a local variable references an object , And escaped the access of the method ( such as static Decorated variable , Object as a parameter , Method has a return value ), Then consider thread safety .
Above m2 In the method , The reference of the formal parameter points to the object in the heap , The object can be modified externally , This leads to thread insecurity , What if the basic data type is used as a formal parameter ? I guess it won't cause thread insecurity ? But overall , When you pass objects , There will be unsafe situations .
3. Stack memory overflow
Program runtime , There are two possible stack errors
- StackOverFlowError: Too many stack frames , for example , If there is no termination condition in the recursive process , Will cause this kind of problem
- OutOfMemoryError: Stack frame memory is too large , The virtual machine cannot apply for enough memory space when dynamically expanding the stack
4. Thread running diagnostics
Case a :cpu Take up too much resolvent :Linux When running some programs in the environment , May lead to CPU The occupation is too high , At this time, it is necessary to locate the occupied area CPU Too high thread
top command , See which process is occupying CPU Too high
First step : Use top Command to see which process is occupying CPU Too high , But it can't be precise to which specific thread
The second step :ps H -eo pid( process id), tid( Threads id), %cpu( Occupy cpu Percent of ) | grep Just passed top The process number found
Use ps The command can further locate which thread caused cpu Occupy too much
The third step :jstack process id( Just found cpu Occupy too much process number )
According to the thread found in step 2 id Find the problematic thread , Then compare with the output in step 3 , You can find the cpu Use too many threads and the corresponding source code line number , Then go to Java Just look in the source code of , Be careful jstack Found thread id yes 16 It's binary , Need to transform
5. Native Method Stack
It's very similar to what the virtual machine stack does , The difference is that : The virtual machine stack executes for the virtual machine Java Method ( That's bytecode ) service , The local method stack is used by the virtual machine Native Method service .
Some with native Keyword method is to need JAVA To call the local C perhaps C++ Method , because JAVA Sometimes you can't directly interact with the underlying operating system , So you need to use the local method stack , Serve with native Keyword method .
3、 ... and 、 Pile up
1. brief introduction
The sole purpose of this memory area is to hold object instances , Almost all object instances and arrays allocate memory here .
characteristic :
- It's thread shared , Thread safety should be considered for objects in heap memory
- There's a garbage collection mechanism
The easiest thing to see here is OutOfMemoryError error , And there will be several forms of expression after this error , such as :
- java.lang.OutOfMemoryError: GC Overhead Limit Exceeded : When JVM When it takes too much time to perform garbage collection and only a small amount of heap space can be recycled , This error will happen .
- java.lang.OutOfMemoryError: Java heap space : If you are creating a new object , There is not enough space in the heap memory to hold the newly created objects , It will cause this error .( Related to the configured maximum heap memory , And subject to the physical memory size . Maximum heap memory available through -Xmx Parameter configuration , If there is no special configuration , Default will be used )
2. Heap memory diagnostics
For heap memory diagnosis, you can use the following tools
- jps Tools See what's in the current system java process
- jmap Tools Check heap memory usage jmap - heap process id
- jconsole Tools Graphic interface , Multifunctional monitoring tools , It can be monitored continuously ,jdk Self contained ;
- jvisualvm Tools
stay terminal Input in jconsole You can open it jconsole Tools
Four 、 Method area
1. brief introduction
The method area belongs to yes JVM A logical area of the runtime data area , Is an area of memory Shared by each thread
When a virtual machine wants to use a class , It needs to read and parse Class File for information , Then store the information in the method area . The method area stores the methods that have been loaded by the virtual machine Class information 、 Field information 、 Methods information 、 Constant 、 Static variables 、 Real time compiler compiled code cache and other data .
The method area is regarded as a block independent of Java Heap memory space
- Method area (Method Area) And Java Pile up , yes Memory area shared by each thread
- Methods in JVM Created at startup , And its actual physical memory space neutralizes Java The heap area can also be discontinuous .
- The size of the method area , Like heap space , You can choose to be fixed size or scalable ..
- The size of the method area determines how many classes the system can hold , If the system defines too many classes , Cause method area overflow , Virtual machines also throw out memory overflow errors : java.lang .OutofMemoryError:PermGenspace(1.8 Before ) perhaps java.lang.OutOfMemoryError: Metaspace(1.8 after ), close JVM This will free the memory in this area . for example : Load a lot of third party jar package ; Tomcat Too many projects deployed (30-50 individual ) ; A large number of dynamically generated reflection classes may cause memory overflow
The constant pool in the following figure refers to Runtime constant pool
What is the relationship between method area and permanent generation and meta space ? The relationship between method area and permanent generation and meta space is very similar Java The relationship between interfaces and classes in , Class implements the interface , The class here can be regarded as permanent generation and meta space , An interface can be seen as a method area , In other words, the permanent generation and meta space are HotSpot Virtual machine to virtual machine specification method area in two ways . also , Permanent generation is JDK 1.8 The previous method area implementation ,JDK 1.8 And later, the implementation of the method area becomes a meta space .
2. Runtime constant pool
First, the constant pool exists in the decompiled .class In file , This .class The file contains basic class information , Constant pool , Class method definition , Virtual machine instructions
The function of constant pool is to query the virtual machine when interpreting these instructions
Constant pool : It's just a watch , The virtual machine instruction finds the class name to execute according to this constant table 、 Method name 、 Parameter type 、 Literal information ;
Runtime constant pool : The constant pool is *.class In the document , When the class is loaded , Its constant pool information will be put into the runtime constant pool , And put the symbols inside ( such as #1) The address becomes the real address ; The constant pool table will be stored in the runtime constant pool of the method area after the class is loaded .
3. String constant pool (StringTable)
String constant pool yes JVM In order to improve performance and reduce memory consumption, for string (String class ) A specially opened area , The main purpose is to avoid repeated creation of strings .
First we need to understand String str = “” This form , It points directly to the constant pool
and String str = new String(“”) Is stored in the heap , But what is stored is a reference to the constant pool
Here is an example
Check the bytecode file after compiling the above code
You can see that it will create a StringBuffer object , It will be s1 and s2 Splice up , This StringBuffer Of course, it's in the pile , So as shown in the figure below , We use it == When comparing , Is the address of the comparison , Of course they are different , One in the string constant pool , One is in the heap ; however jdk1.7 The post string constant pool is also in the heap , It may be in different spaces in the heap , That leads to the difference in the following figure ?
reflection : Why are the results of these two different ?
public static void main(String[] args) {
String a=new String("ab")+new String("c");
a.intern();
String b="abc";
System.out.println(a==b);//true
}
public static void main(String[] args) {
String a=new String("ab")+new String("c");
String b="abc";
a.intern();
System.out.println(a==b);//false
}
answer :intern() Method , When calling intern When the method is used , If the constant pool already contains one equal to this String Object's string , Then return the string in the pool . otherwise , take intern The returned reference points to the current string
In the first program , Because there are no constants in the constant pool “abc” therefore , Will create... In the constant pool “abc”, And will a Pointing to it
In the second program , Because the constant pool already has “abc”, In the call , There is a return value , But no will a Point to constant pool , therefore a Or point to the heap , The final result is not equal
4.StringTable The location of
JDK1.7 Before , The string constant pool is stored in the permanent generation .JDK1.7 String constant pool and static variables have been moved from permanent generation Java In the pile .
JDK 1.7 Why move the string constant pool to the heap ?
Mainly because the permanent generation ( Method area implementation ) Of GC Recycling efficiency is too low , Only in the whole pile (Full GC) Only when it's executed GC.Java There are usually a large number of created strings waiting to be recycled in the program , Put the string constant pool in the heap , It can reclaim string memory more efficiently and timely .
5.StringTable Performance tuning
1. because StringTable By HashTable Realized , Therefore, we can appropriately increase HashTable Number of barrels , To reduce the time required for strings to be put into the string pool ( Reduce the probability of hash collision )
-XX:StringTableSize= Number of barrels ( The minimum setting is 1009 above , Otherwise, it will throw the exception )
2. Consider whether you need to pool string objects ( Can pass intern Methods to reduce repeated entry into the pool ( So as to reduce the large amount of memory occupied by data ))
5、 ... and 、 Direct memory
1. Introduction to direct memory
Direct memory is not part of the VM runtime data area , It's not the memory area defined in the virtual machine specification , But this part of memory is also frequently used . And it can also lead to OutOfMemoryError Error occurred .
Direct memory not used , It will cause you to experience the buffer twice , The efficiency is not high
Use direct memory
边栏推荐
- Ppt template and material download website (pure dry goods, recommended Collection)
- 模拟卷Leetcode【普通】1705. 吃苹果的最大数目
- OpenGL三维图形绘制
- MySQL master-slave delay solution
- Two schemes of unit test
- Recommended by Alibaba P8, the test coverage tool - Jacobo is very practical
- Druid monitoring - Introduction to JMX usage and principle
- go mod module declares its path as: gtihub. com/xxx-xx but was required as:xx-xx
- 平台化,强链补链的一个支点
- Screen automatically generates database documents
猜你喜欢
E-commerce campaign Guide
平台化,强链补链的一个支点
C language for calculating the product of two matrices
JVM 内存结构 详细学习笔记(一)
Markdown editor Use of MD plug-in
Troublesome problem of image resizing when using typora to edit markdown to upload CSDN
C语言指针(中篇)
Recommended by Alibaba P8, the test coverage tool - Jacobo is very practical
【Istio Network CRD VirtualService、Envoyfilter】
面试题:高速PCB一般布局、布线原则
随机推荐
MySQL master-slave delay solution
Original collection of hardware bear (updated on May 2022)
Two schemes of unit test
硬件大熊原创合集(2022/06更新)
C语言指针(特别篇)
ChaosBlade:混沌工程简介(一)
C语言指针(中篇)
Unityshader introduction essentials personal summary -- Basic chapter (I)
LED模拟与数字调光
go mod module declares its path as: gtihub. com/xxx-xx but was required as:xx-xx
Common short chain design methods
Serial port experiment - simple data sending and receiving
Selenium automation integration, eight years of testing experience, soft test engineer, an article to teach you
How to realize sliding operation component in fast application
Digital triangle model acwing 1027 Grid access
模拟卷Leetcode【普通】1706. 球会落何处
Count the number of words C language
On December 8th, 2020, the memory of marketing MRC application suddenly increased, resulting in system oom
Newly found yii2 excel processing plug-in
测试人一定要会的技能:selenium的三种等待方式解读,清晰明了