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

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>

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();
    }
}

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
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)