Location>code7788 >text

Interviewer: jvm tuning, which area is it mainly targeting and what is the jvm memory structure like?

Popularity:432 ℃/2024-07-21 00:20:32

As a Java programmer, in the daily development, do not have to like C / C + + programmers, for each memory allocation to worry about, the JVM will be for us to carry out automatic memory allocation and recovery, to facilitate our development. But once a memory leak or memory overflow occurs, if the Java memory structure is not clear, it will be a very troublesome thing! In this article, I will explain the Java memory structure.

Interview Tips

  1. Talking about Java memory structure? What are all the components? Which are thread-shared? Which are thread-private?
  2. When we usually talk about JVM tuning, which area is it mainly targeting? What is the largest piece of this area? What is it mainly used to store?
  3. What does the Java VM stack store?
  4. What is the purpose of the program counter? Do program counters go OOM when out of memory?
  5. Chat about your thoughts on method zones? What is the evolution of method zones in different JDK versions?

Do you know all of these questions by heart? After reading this article I am sure you will have the answers in your mind!

JVM Architecture

Platform-independence of the JVM

jvm与操作系统

  1. A computer's CPU, memory, graphics card, etc. are part of thesoftware
  2. The commonly used MacOs, Windows, and Linux belong to the computer'soperating system
  3. And Java's virtual machine, theThe JVM runs on the operating systemOn top of that, there is no direct connection with the hardware, and the JVM is the fundamental reason why Java can be cross-platform.

JVM Architecture

image-20240630174946980

1. Class Loader

The role of the class loader is toLoading class files into memoryThe answer is the Class Loader. Of course, not just any .class file can be loaded, but the Class Loader loads the class file as it is. The answer is the Class Loader, but of course, not just any .class file can be loaded.Formatting requirements apply

2. Execution Engine

The Class Loader is only responsible for loading as long as it matches thefileThe structure just loads, as far as being able to(of a computer) runThe Execution Engine is not responsible for this, it is. Execution Engine is also called Interpreter.Responsible for interpreting commands and submitting them to the operating system for execution

3. Native Interface

The role of the local interface is toIntegration of different programming languages for JavaIt was originally intended to be a fusion of C/C++ programs, and Java was born at a time when C/C++ was running amok.A special area of memory is set aside to handle code marked as native

4. Runtime data area

The runtime data area isFocus of the entire JVM. All the programs we write are loaded here before they start running, and the focus will be on the runtime data area below.

JVM execution flow

Of course, the specific implementation details of different VMs are not different, and now the more commonly used version of JDK8 is theSun HotSpot VM with BEA JRockit VMThe version of the JDK developed after the merger.

Here's one.Java files are loaded and executedworkflow

JVM架构

run-time data area

The runtime data area is the most important part of the JVM. It is also the area we need to focus on when tuning.

Runtime data is distinguished as:program counterJava virtual machine stacklocal method stackJava heapmethodology area

included among these

  • Thread Private: program counters, virtual machine stacks, local method stacks
  • thread sharing: heap, method area, off-heap memory (Java7's permanent generation or JDK8's metaspace, direct memory)

JDK 1.8 is slightly different from previous versions, so we'll use JDK 1.7 and JDK 1.8 as examples.

JDK 1.7

java-runtime-data-areas-jdk1.7

JDK 1.8

java-runtime-data-areas-jdk1.8

program counter

The program count register (Program Counter Register), Register is named after the CPU's registers, which store instruction-related thread information, and the CPU can only run if it loads data into the registers. It is a very small piece of memory, almost negligible. It is also the fastest memory area

  1. PC registers in the JVM are an abstract analog of physical PC registers. It can be thought of as the bytecode that the current thread is executing theline number indicator. The interpreter works by changing the value of this counter to select the next bytecode instruction to be executed, branching, looping, jumping, exception handling, thread recovery and other functions rely on this counter to complete.

  2. Since the Java VM's multithreading is done through theThread rotation switching, which is implemented by allocating processor execution time in such a way that at any given moment in time, theEach processor (or core in the case of multicore processors) executes instructions in only one thread.. Therefore, in order to recover to the correct execution position after a thread switch, theEach thread needs to have a separate program counter

  3. There is only one method being executed in a thread at any given time, also known as thecurrent methodIf the current thread is executing a Java method, the program counter records the JVM byte code instruction address. The program counter records the JVM bytecode instruction address if the current thread is executing a Java method, or an unspecified value (undefined) if it is executing a native method

  4. The program counter is the only one that does not appearOutOfMemoryError region of memory, which has a life cycle that is consistent with the thread.

jvm-pc-counter

Java virtual machine stack

Each thread creates a virtual machine stack when it is created, which internally holds one of theStack FrameIt corresponds to the time and againJava Method Calls, which is thread-private and has the same lifecycle as the thread.

1、The internal structure of the stack

everyonestack frame (computing)(Stack Frame) is stored:

  • Local Variables table (Local Variables): Mainly stores compile-time-knowableVarious data types(boolean, byte, char, short, int, float, long, double), object references (reference type, which is different from the object itself and may be a reference pointer to the starting address of the object or to a handle representing the object or other location associated with this object)

  • Operand Stack: Mainly used for storing methods generated during the execution of theIntermediate calculations. Also, temporary variables generated during the computation are placed on the operand stack.If a method is called with a return value, the return value is pressed into the operand stack of the current frame.

  • Dynamic Linking: Method references that point to the runtime constant pool.The constant pool of a Class file holds a large number of symbolic references such as method references.When a method wants to call another method, it needs to convert the symbolic references pointing to the method in the constant pool into direct references to it in the memory address. This process is also known asdynamic connection

  • Method Return Address: Address where the method exits normally or abnormally

PS: Variables in the local variables table are also importantgarbage collection root nodeThe object is not recycled as long as it is directly or indirectly referenced by a local variable table.

img

2、Stack execution process

  • There are only two operations that the JVM performs directly on the virtual machine stack: the method callpush onThe end of the execution of the methodsend a package to a warehouse
  • There will be only one active stack frame in the thread at any one time, i.e. (top-of-stack stack frame) is valid, this stack frame is called thecurrent stack frame(Current Frame), the method corresponding to the current stack frame is thecurrent method(Current Method), the class that defines this method is thecurrent class(Current Class)
  • If in the methodOther methods are calledcorrespondingNew stack framewill be created and placed at the top of the stack, called the new current stack frame
  • Stack frames contained in different threads are not allowed to reference each other, i.e., theIt is not possible to reference another thread's stack frame in a stack frame

jvm-stack-frame

3、Stack exception

  • *Error If the memory size of the stack is not allowed to expand dynamically, then when a thread requests a stack that is deeper than the current maximum depth of the Java VM stack, it throws a*Error Error.

  • OutOfMemoryError If the stack's memory size is dynamically expandable, and if the VM is unable to claim enough memory space when dynamically expanding the stack, it throws aOutOfMemoryErrorException.

local method stack

The local method stack and the Java virtual machine stack play very similar roles

  • The difference between the two is:The virtual machine stack executes Java methods for the virtual machine (a.k.a. bytecode) services, whileThe native method stack serves the Native methods used by the VM.

  • When a local method is executed, a stack frame is also created on the local method stack to hold the local variable table, operand stack, dynamic links, and exit information for that local method.

  • When the method finishes executing the corresponding stack frame will also go out of the stack and release the memory space, and there will also be a*Error cap (a poem)OutOfMemoryError Two anomalies.

  • existHotspot JVM in which the local method stack and the VM stack are directly combined into one

Java heap

The stack is the unit of runtime, while the heap is the unit of storage

The Java heap is the largest chunk of memory managed by the Java Virtual Machine and is used by theShared by all threads

PS:There are a lot of details about the Java heap that can be dug into, such as heap generation and object creation and recycling, etc., and I'll devote an article to it.

1. Storage contents of the heap

The sole purpose of this memory region is toStoring object instances, where almost all object instances as well as data are allocated memory.Member variable names and values are stored in the heap, whose life cycle is the same as that of the object.

In the Java world, "almost" all objects are allocated on the heap. However, as the JIT compiler evolves and escape analysis techniques mature, allocation on the stack and scalar replacement optimization techniques will lead to some subtle changes, and the allocation of all objects to the heap will gradually become less and less "absolute". absolute". Since JDK 1.7, escape analysis has been turned on by default, so that if an object reference in some method is not returned or used outside (i.e., not escaped), then the object can be allocated memory directly on the stack.

2. Heap partitioning and garbage collection

For efficient garbage collection, the virtual machine puts the heap memorylogicallyDivided into three regions (the only reason to split generations is to optimize GC performance):

  • Emerging Belt (Younger Generation): Both new subjects and subjects who have not reached a certain age are in the new generation
  • Old age (retirement area): Objects that have been used for a long time should have more memory space in older generations than in younger ones.
  • Metaspace (called permanent generation before JDK 1.8): Some methods manipulate temporary objects, etc., which occupied JVM memory before JDK1.8, but directly use physical memory after JDK1.8.

img

3. Exceptions appearing in the heap

The most likely thing to come out of the pile here isOutOfMemoryError Errors, for example:

  • : GC Overhead Limit Exceeded: This error occurs when the JVM spends too much time performing garbage collection and can only reclaim a small amount of heap space.

  • : Java heap space : This error is raised if there is not enough space in heap memory to hold the newly created object when it is created. (Relates to the configured maximum heap memory and is limited by the size of physical memory. The maximum heap memory can be set with the-XmxParameter configuration, if not specifically configured, default values will be used, see details:Default Java 8 max heap sizeopen in new window)

methodology area

The method area is a logical part of the JVM's runtime data area and is a memory area shared by all threads.

1, What is the relationship between method area and permanent generation and meta-space?

The relationship between the method area and the permanent generation and meta-space is very similar to the relationship between interfaces and classes in Java, where the class implements the interface, the class can be regarded as the permanent generation and the meta-space, and the interface can be regarded as the method area, that is, the permanent generation and the meta-space are the two ways of implementing the method area in the virtual machine specification of the HotSpot virtual machine. That is to say, the permanent generation is the implementation of the method area before JDK 1.8, and the implementation of the method area in JDK 1.8 and later becomes the metaspace.

method-area-implementation

2. Storage contents of the method area

When a virtual machine wants to use a class, it reads and parses the Class file for information and then stores the information in the method area. The method area stores the methods that have been loaded by the virtual machine.Class information, field information, method information, constants, static variables, on-the-fly compiler compiled code cache and other data. After loading classes and structures into the virtual machine, the correspondingrun-time constant pool

Runtime Constant Pool (RCP)is part of the method area in the virtual machine specification, and after loading classes and structures into the virtual machine, the corresponding runtime constant pool is created; and the string constant pool is where the constant strings are stored during this process. So from this point of view, the string constant pool is part of the method area in the virtual machine specification, which is aLogical concepts; while the heap area, the permanent generation, and the meta-space are the actual storage locations.

3, method area in JDK6, 7, 8 in the evolution of details

JDK version Is there a permanent generation and where is the pool of string constants placed? What are the actual parts of the method area that are logically standardized and implemented?
jdk1.6 and before There is a permanent generation, a pool of runtime constants (including a pool of string constants), and static variables are stored on the permanent generation This period method area is implemented in HotSpot by the permanent generation, to the extent that theTo say method area in this period means permanent generation
jdk1.7 There are permanents, but they have been progressively "de-permanentized", with the string constant pool and static variables removed and stored in the heap; This period method area is covered in HotSpot by thePermanent Representative(type information, fields, methods, constants) andheap up(string constant pools, static variables) Co-implementation
jdk1.8 and later Eliminate persistent generation, type information, fields, methods, and constants are kept in meta-space in local memory, but string constant pools and static variables remain in the heap This period method area is used in HotSpot by the local memory of thespace (math.)(type information, fields, methods, constants) andheap up(string constant pools, static variables) Co-implementation

method-area-jdk1.6

method-area-jdk1.7

reference article

  1. [002] Ten Minutes to Understand Java Memory Structure

  2. Memory Partitioning of JVM / Memory Structure / Memory Regions / JVM Memory Model

  3. JVM Basics - JVM Memory Structure

  4. Java memory regions in detail (emphasis added)

  5. Introduction to the overall JVM architecture and tuning parameters