JVM defines the data regions used during execution of several programs. Some data in this region is created at JVM startup and destroyed at JVM exit. Other data depends on every thread. It is created when the thread is created and destroyed when the thread exits.
Program counters
The program counter is a small memory space and can be seen as the row number indicator of the bytecode executed by the current thread. This counter is required for basic functions such as branch, loop, jump, exception handling, and thread recovery.
Java Virtual Machine multithreading is implemented by switching threads in turn and allocating the processor execution time. At any definite moment, a single processor (for a multi-core processor, It is a kernel) only the commands in one thread are executed. Therefore, in order for the thread to be switched back to the correct execution position, each thread requires an independent program counter. The counters between each thread do not affect each other and are stored independently, we call this type of memory area"Thread privateMemory.
If the thread is executing a Java method, this counter records the address of the Virtual Machine bytecode instruction being executed; if the Natvie method is being executed, this counter value is null (Undefined ).
This memory region is the only region that does not specify any OutOfMemoryError conditions in the Java Virtual Machine specification.
Virtual Machine Stack
The thread is private, and its lifecycle is the same as that of the thread. The VM stack describes the Memory Model of Java method execution:When each method is executed, a Stack Frame is created at the same time to store information such as the local variable table, Operation Stack, dynamic link, and method exit..
An animation is produced by the result of continuous switching of one frame or one frame. In fact, the operation of a VM is similar to that of an animation, each program running in a virtual machine is also generated by switching many frames, but these frames store local variables, operand stacks, and dynamic links of methods, method return address and some additional information. The process of calling each method until execution is complete corresponds to the process of a stack frame in the VM Stack from the inbound stack to the outbound stack.
For the execution engine, only the stack frame at the top of the stack is valid in the active thread.Current stack frameThe method associated with this stack frame is calledCurrent Method.All bytecode commands run by the execution engine only operate on the current stack frame..
Local variable table
A local variable table is a storage space for variable values,Used to store local variables defined inside method parameters and Methods. When the Java program is compiled into a Class file, the maximum capacity of the local variable table to be allocated by the method is determined in the max_locals data item of the Code attribute of the method.
The capacity of the local variable table isVariable slot(Slot) is the smallest unit, A Slot in a 32-bit virtual machine can store data types of up to 32 bits (boolean, byte, char, short, int, float, reference, and returnAddress ).
The reference-type virtual machine specification does not specify its length, but in general, virtual Machine implementation should at least be able to directly or indirectly find the object type data in the starting address index and Method Area of the object in the Java heap.
The returnAddress type serves bytecode instructions jsr, jsr_w, and ret. It points to the address of a bytecode instruction.
A virtual machine uses a local variable table to pass parameter values to the Parameter Variable list.If it is an instance method (non-static), the Slot of the 0th-bit index of the local variable table is used by default to pass the reference of the object instance to which the method belongs and access through this in the method.
Slot can be reused. When the variables in the Slot are out of scope, the next Slot allocation will overwrite the original data. Slot references to objects will affect GC (if referenced, it will not be recycled ).
The system does not assign an initial value to a local variable (both instance variables and class variables are granted an initial value). That is to say, there is no preparation stage like a class variable.
Operand Stack
Like the local variable area, the operand stack is also organized into an array in characters. But what is different from the former is that it is not accessed through indexes, but accessed through standard stack operations-pressure stack and out stack. For example, if a command pushes a value to the operand stack, another command can pop up later to use this value.
The VM stores data in the operand stack in the same way as in the local variable area: such as int, long, float, double, reference, and returnType storage. Values of the byte, short, and char types are also converted to int before being pushed to the operand stack.
The virtual machine uses the operand stack as its Workspace-most commands need to pop up data from here, execute operations, and then compress the results back to the operand stack. For example, the iadd command will pop up two integers from the operand stack and execute the addition operation. The result is compressed back to the operand stack. Let's take a look at the following example, it demonstrates how the virtual machine adds two int-type local variables and then saves the result to the third local variable:
beginiload_0 // push the int in local variable 0 ontothe stackiload_1 //push the int in local variable 1 onto the stackiadd // pop two ints, add them, push resultistore_2 // pop int, store into local variable 2end
In this bytecode sequence, the first two commands, iload_0 and iload_1, are stored in local variables and the integers 0 and 1 are pushed into the operand stack, then, the iadd command pops up the two integers from the operand stack and adds the result to the operand stack. The fourth instruction, istore_2, pops up the result from the operand stack and stores it to the location where the local variable area index is 2. The State Changes of the local variables and the operand Stack are described in detail in this process. The local variables and the operand stack areas that are not used in the figure are expressed in blank spaces.
Dynamic connection
When a virtual machine is running, a large number of symbolic references are saved in the runtime constant pool. These symbolic references can be seen as indirect references of each method. If you want to call A method that represents stack frame A that represents stack frame B, the method call command of this virtual machine uses the symbol reference of Method B as A parameter, however, because symbolic references do not direct to the memory location that represents Method B, you must convert the symbolic references to direct references before calling, then you can access the real method through direct reference.
If the symbolic reference is converted to a direct application in the class loading stage or when used for the first timeStatic ParsingIf it is converted to direct reference during running, the conversion becomesDynamic connection.
Return address
Method return can be divided into two situations: one is normal exit. After exiting, the system determines whether to pass the return value to the upper-layer caller based on the method definition, one is the end of the method caused by an exception. In this case, the call method of the upper layer is not returned.
However, no matter the method ends, when exiting the current method, it will jump to the position where the current method is called. If the method Exits normally, the value of the PC counter of the caller can be used as the return address. If the caller exits due to an exception, it needs to be determined through the exception handling table.
A call of a method corresponds to an inbound and outbound operation of the stack frame in the Virtual Machine stack. Therefore, when a method exits, it may do the following: restore the local variable table and the operand stack of the Upper-layer method. If a return value exists, the return value is pushed to the operand stack of the caller's stack frame, the PC counter value will also be adjusted to the next instruction in the method call entry.
Exception
In the Java Virtual Machine specification, two exception conditions are defined for the Virtual Machine Stack: If the stack depth requested by the thread is greater than the depth allowed by the virtual machineStackOverflowErrorException; if the Virtual Machine stack can be dynamically extended (currently most Java virtual machines can be dynamically extended, but the Java Virtual Machine specification also allows a fixed-length Virtual Machine stack ), it will be thrown when the extended memory cannot be appliedOutOfMemoryErrorException.
Local method Stack
The local method stack (Native MethodStacks) plays a very similar role with the Virtual Machine stack. The difference is that the virtual machine stack serves the virtual machine to execute Java methods (that is, bytecode, the local method stack is the Native method service used by virtual machines. The language, usage, and data structure of the methods in the local method Stack are not mandatory in the virtual machine specification. Therefore, the specific virtual machine can implement it freely. Even some virtual machines (suchSun HotSpot Virtual Machine) directly combines the local method stack and Virtual Machine stack into one.
Like the Virtual Machine stack, StackOverflowError and OutOfMemoryError are thrown in the local method stack area.
Heap
Heap is the largest memory managed by Java virtual machines. Java heap is a memory area shared by all threads. It is created when the VM is started.The only purpose of this memory area is to store object instances., Almost all object instances are allocated memory here. However, with the development of JIT compiler and the gradual maturity of escape analysis technology, stack allocation and scalar replacement optimization will lead to some subtle changes, all objects are allocated to the stack and gradually become "absolute.
Heap is the main area for managing the garbage collector.Therefore, it is often called"GC heap".
The heap size can be passed through-Xms (Minimum) and-Xmx(Maximum) parameter settings.-Xms is the minimum memory applied for when JVM is started. By default, it is 1/64 of the physical memory of the operating system but less than 1 GB.-Xmx is the maximum memory that JVM can apply, the default value is 1/4 of the physical memory but less than 1 GB. By default, when the free Heap memory is less than 40%, the JVM will increase the Heap to the size specified by-Xmx. You can use-XX: minHeapFreeRation = to specify this ratio column. When the free heap memory is greater than 70%, JVM will reduce the heap size to the size specified by-Xms. You can specify this ratio column through XX: MaxHeapFreeRation =, to avoid frequent Heap size adjustment during running, the value of-Xms is usually the same as that of-Xmx.
From the perspective of memory collection, since the collectors are basically using generational collection algorithms, the Java heap can also be subdivided into the new generation and old generation;
New Generation:The newly created objects of the program are allocated memory from the new generation., New GenerationEden SpaceSame size as the twoSurvivor Space(Generally referred To as S0 and S1 or From and ).-XmnParameter to specify the size of the new generation.-XX: specified vorrationTo adjust the size of the Eden Space and elastic vorspace.
Old Age: It is used to store objects that are still alive after many new generations of GC, such as cache objects. Newly created objects may also directly enter the old age. There are two main situations: 1. large objects, you can set the startup parameters.-XX: PretenureSizeThreshold= 1024 (in bytes, the default value is 0), which means that when the number of bytes exceeds the upper limit, it is not distributed in the new generation, but directly distributed in the old generation. 2. Large Array objects, and no external objects are referenced in the array.
The memory size occupied by the old age is the value corresponding to-Xmx minus the value corresponding to-Xmn.
If the heap does not have memory for instance allocation and the heap cannot be extended, an OutOfMemoryError will be thrown.
Method Area
The method area is inside a jvm instance,Type informationStored in a memory logical zone called a method zone. The type information is extracted from the class file by the Class Loader during class loading. Class (static) variables are also stored in the method area.
To put it simply, the method area is used to store type metadata information. A class file is a representation of a class before it is used by a Java Virtual Machine. Once this class is used, the Java Virtual Machine will load, connect (verify, prepare, and parse) it and initialize it. The load (the result is the transformation from the. class file to a specific data structure in the method area. This data structure stores the following information:
Type information
Full qualified name of this type
Full qualified name of direct superclass of this type
Is this type A class type or an interface type?
This type of access modifier
List of fully qualified names of any direct superinterface
Field Information
Field name
Field Type
Field Modifier
Method Information
Method Name
Method return type
Number and type of method parameters (in order)
Method Modifier
Other information
All class (static) variables except Constants
A pointer to ClassLoader
A pointer to a Class Object
Constant pool (constant data and symbol reference for other types)
JVM maintainsConstant pool. The constant pool is an ordered set of constants used for this type, including actual constants (string, integer, and floating point constants) and symbolic references to types, fields, and methods. The data items in the pool are the same as the array items,It is accessed through an index..
The metadata of each class accesses the metadata in the method area, whether it is to construct an instance of the class or call a method of an object of the class.
When constructing an object, JVM will allocate space to the object in the heap, these spaces are used to store the attributes of the current object instance and the instance attributes of its parent class (and these attributes are obtained from the method area). Note, this is not just about allocating space for the instance attributes of the current object, but also assigning the instance attributes of the parent class. Now we can answer the first question, that is, when a subclass of the parent class is instantiated, JVM also constructs an object of the parent class. This problem can also be confirmed from another perspective: when calling the constructor of the current class, the constructor of its parent class will be called first until the Object is called, and the call of constructor means the creation of the instance, therefore, when subclass is instantiated, the parent class will certainly be instantiated.
The class variable is shared by all instances of the class, and you can access it even if there is no class instance.These variables are only related to classes, so in the Method AreaAnd become a logical part of the class data. Before JVM uses a class, it must allocate space for each non-final class variable in the method area.
The method area has the following features:
1. The method area is thread-safe. Since all threads share the method area, data access in the method area must be designed to be thread-safe. For example, if two threads attempt to access the same class in the Method Area and the class has not been loaded into JVM, only one thread is allowed to load it, and other threads must wait.
2. The size of the method area does not need to be fixed. The JVM can be dynamically adjusted as needed. At the same time, the method area is not necessarily continuous. The method area can be freely allocated in a heap (or even the JVM's own heap.
3. The method area can also be garbage collected. When a class is not used (not accessible), JVM will uninstall the class for garbage collection.
You can use-XX: PermSizeAnd-XX: MaxPermSizeThe parameter limits the size of the method area.
For developers who are used to developing and deploying programs on HotSpot virtual machines, many people are willing to refer to the method area as"Permanent generationPermanentGeneration is essentially not equivalent to the two because the design team of the HotSpot Virtual Machine chooses to extend GC generation collection to the method area, or use permanent generation to implement the method area. For other virtual machines (such as BEA JRockit and IBM J9), the concept of permanent generation does not exist.
Relatively speaking, the garbage collection behavior rarely occurs in this area, but it does not mean that the data enters the method area, just as the permanent name is "permanent. The memory recovery target in this region is mainly for the collection of constant pools and the uninstallation of types.
When the method area cannot meet the memory allocation requirements, an OutOfMemoryError error is thrown.
Summary
Name |
Features |
Function |
Configuration parameters |
Exception |
Program counters |
Small memory usage, private thread, Same lifecycle as thread |
It is roughly a bytecode line number indicator |
None |
None |
Virtual Machine Stack |
The thread is private. The life cycle is the same as that of the thread, and continuous memory space is used. |
Memory Model for Java method execution, storing information such as local variable tables, Operation stacks, dynamic links, and method egress |
-Xss |
StackOverflowError OutOfMemoryError |
Java heap |
Thread sharing. The life cycle is the same as that of a virtual machine. Continuous memory addresses are not used. |
Saves object instances. All object instances (including arrays) must be allocated on the stack. |
-Xms -Xsx -Xmn |
OutOfMemoryError |
Method Area |
Thread sharing. The life cycle is the same as that of a virtual machine. Continuous memory addresses are not used. |
Stores information about classes loaded by virtual machines, constants, static variables, and Code Compiled by the real-time compiler. |
-XX: PermSize: 16 M -XX: MaxPermSize 64 M |
OutOfMemoryError |
Runtime constant pool |
A part of the method area is dynamic. |
Store literal and symbolic references |
|
|
Direct Memory
Direct Memory is not part of the data zone during virtual machine running hours, nor is it the Memory area defined in Java Virtual Machine specifications. However, this part of Memory is also frequently used, it may also cause an OutOfMemoryError exception, so we will explain it here.
The NIO (NewInput/Output) class is added to JDK 1.4, and an I/O Method Based on Channel and Buffer is introduced, it can use the Native function library to directly allocate off-heap memory, and then use a DirectByteBuffer object stored in the Java heap as a reference to this memory. This can significantly improve the performance in some scenarios, because it avoids repeated data replication in the Java and Native stacks.
Comparison Between Stack and stack
Java memory is often divided into Heap memory and Stack memory. This method is rough, and the Division of Java memory areas is actually far more complex than this. The popularity of this division method only shows that the memory areas most concerned by most programmers and most closely related to object memory allocation are these two.
The heap is flexible but insecure. For objects, we need to dynamically create and destroy them. It cannot be said that the created objects are not destroyed, and the previously created objects cannot be destroyed. In this case, our programs will be unable to perform anything, therefore, Java uses heap to store objects. Once the object in the heap is destroyed, if we continue to reference this object, the famous NullPointerException will appear, this is the disadvantage of the heap-the wrong reference logic can only be found at runtime.
Stack is not flexible, but strict, secure, and easy to manage. As long as the above references are not destroyed, the following references must be still in place. In most programs, variables are defined first, advanced stacks are referenced, and those defined later are then added to the stack. At the same time, variables and references within a block are pushed to the stack when the block enters and the block ends. After understanding this mechanism, we can easily understand the concept of the scope of various programming languages, this is also the advantage of stack-the wrong reference logic can be found during compilation.
STACK: stores references and basic data types.
Heap -- used to store new object instances.
Memory overflow and Memory leakage
Memory OverflowOut of memoryWhen a program applies for memory, there is not enough memory space for it to use, and an out of memory occurs. For example, if an integer is applied, but a long value is saved to it, that is, memory overflow.
Memory leakageMemory leakAfter applying for memory, the program cannot release the applied memory. The memory leakage hazard can be ignored once, but the memory leakage accumulation is serious, no matter how much memory, sooner or later.
Memory leak will eventually cause out ofmemory.
Java heap memory OutOfMemoryError is the most common memory overflow exception in actual applications. When a Java heap memory overflow occurs, the exception stack information "java. lang. OutOfMemoryError" will be followed by the prompt "Java heapspace ".
To solve the exceptions in this region, the general method is to analyze the dump snapshot by using the Memory Image Analysis Tool (such as Eclipse Memory Analyzer, the key point is to check whether the objects in the Memory are necessary, that is, to first identify whether there is a Memory Leak (Memory Leak) or Memory Overflow (Memory Overflow ).
In case of Memory leakage, You can further use the tool to view the reference chain of the leaked object to GC Roots. Therefore, you can find the path through which the leaked objects are associated with GC Roots, and the garbage collector cannot automatically recycle them. You can accurately locate the location of the leaked code by understanding the type information of the leaked object and the GC Roots reference chain.
If there is no leakage, that is, the objects in the memory must still be stored, check the heap parameters (-Xmx and-Xms) of the virtual machine ), compare with the physical memory of the machine to see if it can be increased. Check the code to see if some objects have a long life cycle and hold status, and try to reduce the memory consumption during the running period.
Memory Allocation Process
1. JVM will try to initialize a memory area for the relevant Java object in Eden Space.
2. When the Eden space is sufficient, the memory application is completed; otherwise, the next step is reached.
3. JVM tries to release all inactive objects in Eden (this belongs to 1 or more advanced garbage collection ). After the Eden is released, if the Eden space is still insufficient for new objects, the system tries to put some active objects in the same vor area.
4. The primary vor area is used as the intermediate swap area of Eden and Old. When the Old area has sufficient space, objects in the primary vor area will be moved to the Old area. Otherwise, objects in the primary vor area will be kept in the primary vor area.
5. When there is not enough space in the Old area, JVM will perform full garbage collection in the Old area (Level 0 ).
6. After full garbage collection, if the primary VOR and Old areas still cannot store some objects copied from Eden, the JVM cannot create a memory area for new objects in the Eden area, the error "outofmemory" appears.
Object Access
Object Access is everywhere in the Java language and is the most common program behavior, but even the simplest access, this Code also involves the association between the three most important memory areas, namely the Java stack, Java heap, and method zone:
Object obj = newObject ();
Assuming that the code appears in the method body, the semantics of the "Object obj" part will be reflected in the local variable table on the Java stack, and will appear as a reference type data. The semantics of the "new Object ()" part will be reflected in the Java heap, forming a block that stores all Instance Data values of the Object type (Instance Data, the structured Memory of each instance field in the Object. According to the specific type and the Object Memory Layout (Object Memory Layout) implemented by the virtual machine, the length of the Memory is not fixed. In addition, the Java heap must contain the address information that can be found for the object type data (such as the object type, parent class, implemented interface, and method, these types of data are stored in the method area.
Because the reference type only specifies a reference pointing to an object in the Java Virtual Machine specification, it does not define the method in which the reference should be located and the specific location of the object accessed to the Java heap, therefore, object access methods implemented by different virtual machines are different. There are two mainstream access methods:HandleAndDirect pointer.
If you use the handle access method, a memory block is allocated to the Java heap as the handle pool. The reference stores the handle address of the object, the handle contains the specific address information of the object instance data and type data.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.