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 ：
- 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
- 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 .
- 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 .
- 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 .
- 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 ”.
- 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 .