This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

Java Virtual Machine (JVM) : Java Virtual Machine (JVM)

JVM memory structure: runtime data region

In fact, for the UPPER layer of the JVM, there is a Java Virtual Machine specification that is customized by Oracle. When we talk about a JVM, we usually mean a specific implementation of a specific JVM specification. For example, we often use the Java virtual machine HotSpot, JDK1.8 is using HotSpot

> java -version
java version "1.8.0_271"
Java(TM) SE Runtime Environment (build 1.8.0_271-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.271-b09, mixed mode)
Copy the code

For example, we often confuse persistent generation before JDK1.8 and meta-space after JDK1.8, which in this article is permanent generation and in that article is meta-space, but in fact both can be considered implementations of method areas in the JVM specification

This article dissected the memory areas of the JVM in as much detail as possible

In fact, knowledge about the JVM can be confusing and confusing, and I strongly recommend that you bookmark and follow it, and review it while you’re still in good spirits


Overall JVM Architecture

The JVM memory region, also known as the runtime data region, is shown in red:

Overall JVM architecture diagram:


JVM memory structure

It is mainly divided into the following areas:

  1. Thread private: program counters, local method stacks, virtual machine stacks
  2. Thread public: method area, heap


Program counter (thread private)

A program counter is a small piece of memory that can be seen as an indicator of the line number of bytecode executed by the current thread. ** It is the only area where the JVM specification does not specify any OutOfMemoryError conditions

The role of the program counter

When multiple threads are executing at the same time, it is not possible for a single thread to occupy CPU resources for a long time, resulting in frequent context switches. Each thread has its own program counter in order to return to the correct position to continue executing

Bytecode interpreter works by changing the value of this counter to select the next byte code instruction to be executed, so as to achieve code flow control, such as: sequential execution, selection, loop, exception handling, etc


What is stored in the program counter?

There is only one method executing on a thread at any time, which is called the current method. The program counter records the ADDRESS of the JVM bytecode instruction if the current thread is executing a Java method, or an unspecified value (undefined) if a native method is executing.


Virtual machine stack (thread private)

Each thread creates a virtual stack at the time of creation, which stores a stack frame. Each method call will have a corresponding stack frame pushed into the stack, and each function call will have a stack frame popped out, following the “first in, first out/last in, first out” principle

As shown in the figure below, method 1 calls method 2, so method 2 pushes method 1 under its body. This process is called pressing the stack. After the current method completes (return or exception), the stack is removed


What’s in the stack

The virtual machine stack stores the stack frames, and each stack frame stores the method local variable table, operand stack, dynamic link, and method exit information

Here’s a general overview of what a few things in the stack do, which will be broken down next time

  • Local variable scale: a set of variable value stores used to store method parameters and local variables defined within the method body, such as within the methodString abc = "abc"; Object reference (The reference type, which is different from the object itself, may be a reference pointer to the start address of the object, a handle to the object, or some other location associated with the object)
  • Operand stack: mainly used to store the intermediate results of the calculation process, and as a temporary storage space for variables during the calculation process
  • Dynamic link: each stack frame can save a point to the current method in the class of runtime constant pool, the aim is to: in the current method, if you need to call other methods can be found in the runtime constant pool corresponding symbol references, then converts symbolic reference to reference directly, then you can directly call the corresponding method, which is the dynamic linking
  • Method return address: The method is normalreturnOn exit, the value of the caller’s PC counter is used as the return address, which is the address of the instruction next to the one that called the method; If an exception exits, the return address is determined by the exception table, which is not normally stored in the stack frame


What exceptions does the virtual stack throw

The memory size of the virtual stack can be either dynamic or fixed

  • StackOverFlowError: When set to fixed size, this exception is thrown if the stack push exceeds the maximum allowable value
  • OutOfMemoryError: When dynamic extension is set, this exception is reported if the system cannot obtain enough memory during the extension


The local method stack functions like the virtual stack and throws the same exceptions. The difference is that the virtual stack serves Java methods while the local method stack serves Native methods

Not all JVMS support native methods. This is because the Java Virtual Machine specification does not explicitly require the language, implementation, data structure, and so on of the native method stack. If the JVM product is not intended to support native methods, you may not need to implement a native method stack

In the Hotspot JVM, the native method stack and the virtual machine stack are directly combined


Heap (thread sharing)

The Java heap is the largest chunk of memory managed by the Java virtual machine. The Java heap is a memory area shared by all threads and is created when the VM starts. The only purpose of this memory area is to hold object instances. Almost all object instances and arrays are allocated here. For this reason, the Java Heap is also the primary area managed by the Garbage collector, and is therefore also known as the Garbage Collected Heap.

Partition of heap memory

For efficient garbage collection, it can be found that the heap is divided into three areas:

  1. Young Generation: New objects and objects that do not reach a certain age are in the New Generation, which is divided into Eden, Survivor0, and Survivor1
  2. Old Generation: Objects that have been used for a long time will enter the Old Generation when they reach their age. The memory space of the Old Generation should be larger than that of the young Generation
  3. Meta-space (Perm area in the figure) : JDK1.8 was not previously called a meta-space, called a permanent generation, either a meta-space or a permanent generation, can be regarded as an implementation of the METHOD area in the JVM specification. The method area has a separate name, non-heap, which should be intended to distinguish it from the Java Heap


How do I configure heap memory

When starting a Java program, you can specify the size of the heap with an argument:

  • -Xms: sets the initial heap memory. By default, the initial heap memory size is: computer memory size /64
  • -Xmx: Sets the maximum heap size. By default, the maximum heap size is: computer memory size /4

To share a small zi si, we usually configure the -xmx and -xms parameters to the same value in order to improve performance by eliminating the need to resize the heap once the garbage collection mechanism has cleaned up the heap

Ex. :

java -Xmx1024m -Xms1024m -jar test.jar
Copy the code


The heap is most prone to outofMemoryErrors, and there are two common error messages:

  1. OutOfMemoryError: GC Overhead Limit Exceeded: this is an error that the JVM will report if it spends too much time in garbage collection and has too little space to collect
  2. OutOfMemoryError: Java Heap space: This error occurs when an object is created and there is not enough memory in the heap to hold the new object


Learn more about the heap through the life cycle of objects in the heap

  1. When a new object is created, it is first created in the new generationThe Eden zone allocates memoryAt this point, the JVM will give the object aage(Can be passed-XX:MaxTenuringThresholdParameter setting)
  2. When the new object is large and the Eden space is short, Minor GC is triggered, killing off the unwanted objects and placing the new object in Eden
  3. Objects that Eden experiences once in a garbage collection are put into Survivor0 and its age is given +1
  4. If garbage collection is triggered again, objects in Survivor0 will be moved to Survivor1 and the age will be +1 again
  5. If the age of an object exceeds the age threshold that we configured to enter the old age, the object is assigned to the old age
  6. When the old age is out of memory, MajorGC will trigger. If the old age is still unable to save the new object, OOM will appear.


Methods area

A method area is a concept defined by the JVM specification. Whether it is a permanent generation before JDK1.8 or a meta-space after JDK1.8, it is an implementation that belongs to the specification. You can think of the method area as an interface in Java code, and the permanent generation and meta space are its concrete implementations

The method area is used to store the type information that has been loaded by the virtual machine, constants, static variables, and the code cache compiled by the just-in-time compiler

How do I configure the size of the meta space

  1. -XX:MetaspaceSize: Sets the initial size of the metadata space
  2. -XX:MaxMetaspaceSize: Sets the maximum size of the metadata space

If you do not specify the size of the meta space, the virtual machine may use up all the available system memory as the class is created

Similarly, since the meta-space uses system memory, any overflow is possible, but it is much less likely. When the meta-space overflows, OutOfMemoryError: MetaSpace will be reported

Note that:

  • For a 64-bit server-side JVM, the default-XX:MetaspaceSizeIs 20.75MB, which is the initial high watermark. Once this watermark is reached, Full GC is triggered and unloads unused classes (i.e. the class loaders corresponding to these classes are no longer alive), and the high watermark is reset. The value of the new high watermark depends on how much space is freed after GC. If the free space is insufficient, then not more thanMaxMetaspaceSize, appropriately increase the value. If too much space is freed, lower the value
  • If the initial high water level is set too low, the adjustment of the high water level will occur many times. The garbage collection logs show that the Full GC is invoked many times. To avoid frequent GC, you can set-XX:MetaspaceSizeSet to a relatively high value.


Reference

The JVM basis – the JVM memory structure | Java stack all knowledge system (pdai. Tech)

JavaGuide – Java memory area

CSDN: What are JVMS and JVM specifications