JVM (2) - JVM memory management

lys0410 2021-01-21 15:00:51
jvm jvm memory management

Need to know JVM How to manage memory , We need to understand the following first JVM The overall architecture :


The following is a separate introduction :

  1. Class loading subsystem : JVM Load the class description data into memory , And check it 、 Parse and initialize , The final form can be JVM Direct use java type
  2. Run time data area :Java Virtual machine is executing Java In the process of the program, the memory it manages will be divided into several different data areas . These areas have their own uses , And when it was created and destroyed , Some regions exist with the start of virtual machine process , Some areas are created and destroyed depending on the start and end of the user thread .
  3. Execution engine : Used to perform JVM Bytecode instruction , There are two main ways , They are interpretation execution and compilation execution . The difference lies in , Interpretation execution is translated into virtual machine instruction execution during execution , Compilation execution is to compile before execution . Explain that execution starts fast , Inefficient execution . Compile implementation , Slow start , High execution efficiency . Garbage collector , Automatically manage the memory of the runtime data area , Clear the useless memory occupation , Free up memory resources .
  4. Local method library , Local library interface : stay jdk At the bottom of the story , There are some implementations that need to be done by calling local methods ( Use c or c++ The method of writing ), This is done by calling the local library interface .

The runtime data area is jvm The most important part of , It's also an area to focus on when tuning . The following highlights this area .

1、 Program counter Program Counter Register

It's a small amount of memory , The function is to record the line number of the bytecode instruction executed by the current thread .

The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to execute , It is an indicator of the flow of program control , Branch 、 loop 、 Jump 、 exception handling 、 Basic functions such as thread recovery rely on this counter . because Java The multithreading of virtual machine is switched by threads in turn 、 The way to allocate processor execution time , At any given moment , A processor ( It is a kernel for a multicore processor ) Will only execute an instruction in a thread . therefore , 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 .

2、 The stack area Stack

Same as the program counter ,Java The virtual stack is also thread-private , It has the same life cycle as a thread .
Java The virtual stack describes Java The thread memory model of method execution : When each method is executed ,Java All virtual machines will create a stack frame synchronously , Used to store local variables 、 The stack of operands 、 Dynamic connection 、 Method exit information . The process of each method being called until it has been executed , This corresponds to the process of a stack frame in the virtual machine stack from push to push .

① Stack frame Stack Frame: Is used to support virtual machine method calls and method execution data structure .

② Local variable table Local Variable Table : Is a set of variable value storage space , Used to store method parameters and local variables defined inside the method . stay Java Compiled into Class When you file , The maximum capacity of the local variable table to be allocated by this method has been determined . The local variometer holds various basic data types known at compile time (boolean、byte、char、short、int、float、long、double)「String Is a reference type 」, Object reference (reference type ) and returnAddress type ( It points to the address of a bytecode instruction )

Variable slot (Variable Slot): The capacity of local variable table is in the smallest unit of variable slot , Each variable slot can be stored 32 Bit length of memory space , for example boolean、byte、char、short、int、float、reference. about 64 Bit length data type (long,double), The virtual opportunity allocates two consecutive Slot Space , That is to say, it's equivalent to putting long and double Data type read and write split into two 32 Bit reading and writing . In the table of local variables, the 0 By default, the variable slot of bit index is used to pass the reference of the object instance to which the method belongs , In the method, you can use the keyword “this” To access this implied parameter .

Slot Reuse :

In order to save stack frame space as much as possible , In the local variable table Slot Can be reused , That is to say, when PC The instruction of a counter is out of the scope of a variable ( completion of enforcement ), So this variable corresponds to Slot It can be used by other variables . advantage : Save stack frame space . shortcoming : Garbage collection behavior that affects the system .
( For example, the big method takes up more Slot, After executing the scope of this method, there is no change to Slot Assign values or clear settings null value , The garbage collector can't reclaim the memory in time .)

③ The stack of operands :

  • The operand stack is also often called the operation stack , It's a first in, then out stack .
  • The maximum depth of the operands stack is also written to at compile time Code Attribute max_stacks In the data item .
  • Each element of the stack of operands can include long and double Any inside Java data type .32 The stack capacity occupied by bit data type is 1,64 The stack capacity occupied by bit data type is 2.
  • At the beginning of the implementation of the method , The operand stack of this method is empty , In the execution of the method , There will be a variety of bytecode instructions to write and extract content from the operand stack , That is, stack out and stack in operations .
  • The data type of the elements in the operand stack must strictly match the sequence of bytecode instructions , for example iadd Instructions , There can be no long And a float Use iadd When the order is added .

 ④ Dynamic links

  • Each stack frame contains a reference to the method that the stack frame belongs to in the runtime constant pool , This reference is held to support dynamic connections during method calls .
  • Class There are a lot of symbol references in the constant pool of the file , The method call instruction in bytecode takes the symbolic reference to the method in the constant pool as the parameter . Some of these symbolic references will be converted to direct references during class loading or the first time they are used , This transformation is called static parsing . The other part will be converted to direct reference during each run , This part is called dynamic linking .

      The function of constant pool : Just to provide some symbols and constants , It is easy to identify the instruction ;

⑤ Back to the exit

    Method return address

    When a method starts executing , There are only two ways to exit this method .

  1. The first is that the execution engine encounters the bytecode instruction returned by any method , At this time, there may be a return value passed to the upper method caller , Whether a method has a return value and the type of the return value depends on which method return instruction is encountered , This method of exit is called “ Normal call completed ”.
  2. Exception encountered during method execution , And this exception is not properly handled in the method body . Whether it's Java Exception generated inside the virtual machine , Or in code throw Exception from bytecode instruction , As long as no matching exception handler is found in the exception table of this method , Will cause the method to exit , This method of exit is called “ Exception call completed ”. The return of this method will not provide any return value to its upper layer callers .

No matter what exit method is adopted , After the method exits , Must return to where the original method was called , The program can continue , Method may need to store some information in the stack frame , To help restore the execution state of its upper calling method . Method exit is actually equivalent to the current stack frame out of the stack , Therefore, the possible operations to be performed when exiting are : Recover the local variable table and operand stack of the upper method , Put the return value ( If any ) Push into the operand stack of the caller stack frame , adjustment PC The value of the counter points to an instruction following a method call instruction, etc .

3. Heap area

 Java The heap is an area of memory Shared by all threads , Created when the virtual machine starts . The sole purpose of this memory area is to hold object instances ,Java In the world “ almost ” All object instances allocate memory here . It should be noted that ,《Java Virtual machine specification 》 There is no detailed partitioning of the heap , So the explanation of heap should be based on the specific virtual machine , We use the most HotSpot Virtual machine as an example to explain .Java The heap is the memory area managed by the garbage collector , So it's also called “GC Pile up ”, Is to do JVM Key areas of tuning part .

①jdk1.7 Middle heap memory model :


  • Young The younger generation

          Young The district is divided into three parts ,Eden The area is exactly the same size as the two Survivor District , among ,Survivor In interval , Only one of them is used at a time , The other one is used to copy the object for garbage collection , stay   Eden When the interval is full ,GC It will move the living objects to the idle ones Survivor In interval , according to JVM The strategy of , After several garbage collections , Still live in Survivor The object of will be moved to Tenured District .

  • Tenured Old age

          Tenured Zone is mainly used to store objects with long life cycle , It's usually some old object , When some objects are Young After a certain number of copy transfers , The object will be transferred to Tenured District , Generally, if the system uses application Level cache , Objects in the cache are often moved to this range .

  • Perm The permanent zone

          Perm It's mainly preserved for generations class,method,filed object , This part of the space generally does not overflow , Unless you load a lot of classes at once , But when it comes to hot deployed application servers , Sometimes java.lang.OutOfMemoryError : PermGen space Error of , The big reason for this error is probably to redeploy every time , But after redeployment , Class class Not unloaded , This has resulted in a large number of class The object is saved in perm in , In this case , Generally, restarting the application server can solve the problem .

  • Virtual District

          The difference between the maximum memory and the initial memory , Namely Virtual District .

②jdk1.8 Heap memory model


It can be seen from the figure ,jdk1.8 The memory model of is made up of 2 Part of it is made up of , The younger generation + The old generation .
The younger generation :Eden + 2*Survivor
Old age :OldGen
stay jdk1.8 The biggest change in Perm District , use Metaspace( Metadata space ) Replaced .
One thing to note is that :Metaspace The memory space occupied is not inside the virtual machine , It's in the local memory space , This is also with 1.7 The biggest difference between the two generations is .

By default jdk1.8 Heap memory allocation :



  If the heap memory size is not specified , The default initial heap memory is of the physical machine memory 1/64, The maximum heap memory is of the physical machine memory 1/4 or 1G.(JDK8 Under the circumstances )

Why? 1.8 Will delete the permanent generation : It's for integration HotSpot JVM And JRockit VM And the effort , because JRockit There is no permanent generation , There is no need to configure permanent generation .

4. Method area

Method area (Method Area) And Java Pile up , Is an area of memory Shared by each thread , It is used to store class information that has been loaded by the virtual machine 、 Constant 、 Static variables 、 Real time compiler compiled code cache and other data .
《Java Virtual machine specification 》 The method area is described as a logical part of the heap , It has an alias called “ Non heap ”(Non-Heap), The purpose is to Java Heap differentiation .
JDK8 Before will HotSpot Virtual machine extends the generational design of collector to method area , So you can think of the permanent generation as the method area ,JDK8 After that, the permanent generation was abandoned , Instead of

5. Native Method Stack

Native Method Stack (Native Method Stacks) 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 for the virtual machine (Native) Method service .

The above is JVM The division of memory and their respective functions , Let's talk about it briefly java Object access to .

Java The program will go through the stack reference Data to manipulate specific objects on the heap .

There are two main access methods: handle and direct pointer :

1、 Use handles to access

Java A block of memory will be divided in the heap as a pool of handles ,reference Is the handle address of the object , The sentence contains the specific address information of the object instance data and the type data

2、 Use direct pointer to access

Java The memory layout of objects in the heap must consider how to place information about access type data ,reference The object address is stored in , If you just access the object itself , There's no need for more overhead of indirect access

The biggest benefit of using handles to access is reference The stable handle address is stored in , When the object is moved ( Moving objects during garbage collection is a very common behavior ) Will only change the instance data pointer in the handle , and reference It doesn't need to be modified .
The biggest benefit of using direct pointers to access is that it's faster , It saves the time cost of a pointer location .HotSpot Virtual machine is realized by pointer access .



  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云