Home Java javaTutorial Detailed explanation of JVM memory model and runtime data area (picture and text)

Detailed explanation of JVM memory model and runtime data area (picture and text)

Oct 16, 2018 pm 05:02 PM
java jvm

This article brings you a detailed explanation (pictures and text) about the JVM memory model and runtime data area. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Java memory model

Detailed explanation of JVM memory model and runtime data area (picture and text)

The purpose of Java's memory model definition is: Masks the differences between memory accesses for various hardware and operating systems.

The Java memory model stipulates that all variables are stored in main memory. Each thread has its own working memory. The working memory saves a copy of the variables in main memory.

Threads can only operate on variables in the working memory, and cannot directly read and write variables in the main memory.

Variable access between different threads needs to be completed through main memory.

1. The relationship between the Java memory model and the Java runtime data area: the main memory corresponds to the Java heap, and the working memory corresponds to the Java stack.

2. The volatile keyword makes the updates of variables visible in real time in each working memory. It is used in the singleton mode of DCL

2. Java runtime data area/memory area

Because the runtime data area of ​​jvm has been improving, so There will be differences between different jdk versions.

1. The jvm memory area before jdk1.7 has a permanent generation

Detailed explanation of JVM memory model and runtime data area (picture and text)

1. Program The role of the counter, because the .java file is compiled into a .class file, serves as a line number indicator for the bytecode executed by the current thread. When the bytecode interpreter works, it selects the next bytecode instruction to be executed by changing the value of this calculator. Each thread has an independent program counter.

2. The local method stack is the stack that executes local native methods. Native methods are implemented by the virtual machine!

3. The Java virtual machine stack describes the memory model when the thread executes the Java method (method). Each method corresponds to a stack frame, and the local variable table in the stack frame stores the basic data type variables and object reference variables in the method.

Detailed explanation of JVM memory model and runtime data area (picture and text)

As shown in the figure above, the local variable table saves the 8 basic type variables and object reference variables declared in the method. Each stack frame also has a reference to the runtime constant pool, which refers to the String type. The following is a classic String object generated interview question!

4. The java heap is the largest piece of memory in the JVM and is shared by all threads. Almost all object instances are allocated here, so the java heap is also the main area for JVM garbage collection. The java heap is divided into the young generation and the old generation; the young generation can be further divided into Eden space, From Survivor space, and To Survivor space.

Detailed explanation of JVM memory model and runtime data area (picture and text)

When we use the new keyword to allocate an object, the object is generated in the java heap.

Let’s analyze the situation when the object is generated.

  1. Because Eden is the largest, newly generated objects are allocated to the Eden space. When the Eden space is almost full, a Minor GC is performed, and then the surviving objects are copied to the From Survivor space. At this time, the Eden space continues to provide heap memory to the outside.

  2. The objects that will be generated later are still placed in the Eden space. When the Eden space is full again, at this time, the Eden space and the From Survivor space will perform a Minor GC at the same time, and then the surviving objects will be Put it in the To Survivor space. At this time, the Eden space continues to provide heap memory to the outside.

  3. The next situation is consistent with 2. When the Eden space is almost full, the Eden space and the To Survivor space perform a Minor GC, and then the surviving objects are placed in the From Survivor space.

  4. The next situation is consistent with 3. When the Eden space is fast or slow, the Eden space and the From Survivor space perform a Minor GC, and then the surviving objects are placed in the To Survivor space.

  5. That is to say, one of the two Survivors is used to provide object storage. When the Eden space and a certain Survivor space are GCed, and the other Survivor space cannot hold the objects that survived the GC; or if the Minor GC has been performed for about 15 times in a row, these surviving objects will be put into the old generation space.

  6. When the old generation space is also full, a Major GC is performed to recycle the old generation space. (Also called Full GC, Full GC consumes a lot of memory and should be avoided)

The young generation uses a copy algorithm: each time Minor GC copies the surviving objects in the Eden area and a Survivor area to another Survivor area. The old generation uses a mark-complement algorithm: each time Major GC moves the surviving objects to one end of the memory space, and then directly cleans up the memory outside the end boundary.

Large objects such as arrays and very long strings enter the old generation space directly.

5. The method area is used to store class information, final constants, static variables and other data loaded by the JVM. The data in the method area is unique in the entire program. The method area also contains a runtime constant pool, which mainly stores literals and symbol references generated during compilation (placed after the class is loaded). The literal of the String object will be put into the runtime constant pool.

Garbage collection in the method area mainly involves the recycling of constants and the unloading of types.

2, jdk1.8 and later jvm memory area, metaspace replaces the permanent generation

Detailed explanation of JVM memory model and runtime data area (picture and text)

The properties of metaspace and permanent generation are the same. They are both implementations of the JVM method area and have the same function. However, the biggest difference between metaspace and permanent generation is that metaspace is not in the virtual machine JVM memory, but uses local memory.

Why use metaspace to replace the permanent generation?

  1. Strings exist in the permanent generation and are prone to performance problems and memory overflows.

  2. It is difficult to determine the size of class and method information, so it is difficult to specify the size of the permanent generation. If it is too small, it will easily cause permanent generation overflow, and if it is too large, it will easily cause the old generation to overflow. .

  3. The permanent generation will bring unnecessary complexity to the GC and the recycling efficiency is low.

Direct memory

NIO added after JDK1.4 introduced IO based on channel channels and buffer buffers, using native functions directly Allocating memory outside the heap significantly improves IO performance and avoids the original BIO copying of data back and forth between the Java heap and the naive heap.

Detailed explanation of JVM memory model and runtime data area (picture and text)

3. Memory allocation when generating String

Reference article: Detailed explanation of string constant pool in Java.

4. Memory situation when generating objects

Let’s analyze our common memory models for generating objects or basic data type variables. This will give you a better understanding of the JVM.

int i =3;, a method corresponds to a stack frame, and the basic data type variables in the method are directly allocated in the stack frame. If it is a static or final basic data type, it is stored in the runtime constant pool, just like String.

Object o1 = new Object();, the object reference (Object o1) is stored in the stack frame, but the object data (new Object()) is stored in the java heap, and the object type data (Class and other information) Stored in the method area.

String s1 = new String("abcd");, use the object declared with new, the object reference (String s1) is stored in the stack frame, and the object data (new String("abcd")) is stored in java In the heap, the string value ("abcd") is stored in the runtime constant pool.

String s2 = "abc", the object reference (String s2) is stored in the stack frame, and the string value ("abc") is stored in the runtime constant pool.

Detailed explanation of JVM memory model and runtime data area (picture and text)

The relationship between the java stack, java heap, and method area is roughly as shown in the above analysis.

3. Various exception analysis

1. java heap memory overflow error OutOfMemoryError

If the java heap is allocated There are too many objects, and the memory space is still not enough after GC. The following test is done by cyclically generating objects to consume memory space.

Related instructions: VM Args: -Xms20m -Xmx40m, indicating that the minimum heap memory allocated by the JVM is 20MB and the maximum is 40MB.

 public static void main(String[] args) {
   while (true) {
     List<object> list = new ArrayList(10);
     list.add(new Object());
   }
 }</object>
Copy after login

2. java stack stack overflow error StackoverflowError

If the stack depth of the java stack is greater than the depth allowed by the JVM, this error will be thrown. The following is a stack test through infinite recursive calls.

Related instructions: VM Args: -Xss128k, indicating that the stack capacity allocated by the JVM is 128KB.

public class StackOOM {
    
    private int length = 1;
    
    public void stackLeak() {
        length++;
        stackLeak();
    }
    
    public static void main(String[] args) {
        StackOOM stackOOM = new StackOOM();
        stackOOM.stackLeak();
    }
}
Copy after login

Detailed explanation of JVM memory model and runtime data area (picture and text)


The above is the detailed content of Detailed explanation of JVM memory model and runtime data area (picture and text). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles