Drunk series: JVM dry goods sorted out after being drunk by an interviewer of a certain factory

Click on the blue font above and select "Star Official Account"

High-quality articles, delivered immediately

99 sets of Java enterprise-level actual combat projects

4000G Architect Information

Lead: The official account will launch a series of technical articles after drinking, all of which are dry goods, hope not to get drunk!

Why do you want to write such an article, because it is very basic, very basic, very basic, and telling important things three times! ! ! Hmph, it’s not because I’m often asked during interviews, hahahahaha????, for this reason, I calmed down and wrote this article cruelly, so that I can deal with ordinary interviewers and also help you. To better understand, this is a fierce battle, let's grind our guns and get ready to do it.

Let us take a look at this picture first, I believe you have seen it many times, this time let us not get drunk or return????, cheers!

(The red box is the data area shared by threads, and the blue box is the data area isolated by threads)

During the execution of the Java program, the Java virtual machine divides the memory it manages into several different data areas. Each of these areas has its own purpose, as well as the time of creation and destruction. Some areas exist with the start of the virtual machine process, and some areas are created and destroyed depending on the start and end of the user thread.

Looking at the above figure, we can clearly distinguish the runtime data into the following parts:

1. ???? Let's have a toast! The first cup of respect, program counter

The program counter is a small memory space, and it can be seen as an indicator of the line number of 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 counter. Basic functions such as branches, loops, jumps, exception handling, and thread recovery all need to rely on this counter to complete. It is thread private, and each thread needs an independent program counter.

If the thread is executing a Java method, the counter records the address of the bytecode instruction of the virtual machine being executed;

If the execution is a Native method, the counter value is empty ( Undefined ).

This memory area is the only area that does not specify any OutOfMemoryError exception in the Java Virtual Machine Specification

Two,???? There are three more glasses after drinking this one! ! ! [Java virtual machine stack]

The thread is private, and its life cycle is the same as that of the thread.

The virtual machine stack describes the memory model of Java method execution: when each method is executed, a stack frame is created to store information such as the local variable table, operand stack, dynamic link, and method exit. The process of each method from invocation to completion of execution corresponds to the process of pushing a stack frame in the virtual machine stack to popping out of the stack

In the Java virtual machine specification, two abnormal conditions are specified for this area: If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, a StackOverflowError exception will be thrown ;

If the virtual machine stack can be dynamically expanded, and sufficient memory cannot be applied for during expansion, an OutOfMemoryError exception will be thrown;

3. The third cup [local method stack]

The functions of the native method stack and the virtual machine stack are similar. The difference between them is: the virtual machine stack serves for the virtual machine to execute Java methods (that is, bytecode); the local method stack is the Native method used by the virtual machine Service; the local method stack also throws StackOverflowError and OutOfMemoryError exceptions.

4. After drinking this cup, there is really only the last one [Java heap]

A memory area shared by all threads, created when the virtual machine starts. The sole purpose of this memory object is to store object instances, and almost all object instances allocate memory here.

The Java heap is the main area managed by the garbage collector, so it can also be called the " GC " heap ( Garbage Collected Heap ), or the "garbage heap", which is a joke. The current garbage collectors all use the generational collection algorithm, so the Java heap is subdivided into: the new generation and the old generation (this part will be explained in detail later); no matter what area is divided, it has nothing to do with the storage content, no matter which area , Stored are all object instances, in order to better reclaim memory, or allocate memory faster.

According to the Java Virtual Machine Specification, the Java heap can be in a physically discontinuous memory space, as long as it is logically continuous. In the implementation, it can be implemented as a fixed size or scalable. The current mainstream virtual machines are implemented in accordance with the scalability ( controlled by -Xmx and Xms ). If there is not enough memory in the heap to complete the instance allocation, and the heap can no longer be expanded, an OutOfMemoryError exception will be thrown .

Just say it's useless, go straight to the talent!

 The code demonstrates the usage size and operating principle of heap memory (enter "-XX:+PrintGCDetails" in Run as ->Run Configurations to view the schematic diagram of heap memory operation)

public class JVMTest {
  
      public static void main(String[] args) {
        
          long maxMemory = Runtime.getRuntime().maxMemory(); //Java虚拟机试图使用的最大内存
          long totalMemory = Runtime.getRuntime().totalMemory(); //Java虚拟机中的内存总量
  
          System.out.println("MAX_MEMORY = " + maxMemory + "(字节)" + (maxMemory / 1024 / 1024) + "MB");
          System.out.println("TOTOL_MEMORY = " + totalMemory + "(字节)" + (totalMemory / 1024 / 1024) + "MB");
      }
  
  }

The result after running is shown in the figure below:

Of course, garbage collection can also be triggered by setting parameters (enter the setting "-XX:+PrintGCDetails" in Run as ->Run Configurations to see the principle of garbage collection mechanism)

public class JVMTest {
  
      public static void main(String[] args) {
        
          long maxMemory = Runtime.getRuntime().maxMemory(); //Java虚拟机试图使用的最大内存
          long totalMemory = Runtime.getRuntime().totalMemory(); //Java虚拟机中的内存总量
  
          System.out.println("MAX_MEMORY = " + maxMemory + "(字节)" + (maxMemory / 1024 / 1024) + "MB");
          System.out.println("TOTOL_MEMORY = " + totalMemory + "(字节)" + (totalMemory / 1024 / 1024) + "MB");
  
          String str = "hello world, JVM!";
          while (true) {
              str += str + new Random().nextInt(88888888) + new Random().nextInt(99999999);
          }
      }
  
  }

Run as shown in the figure below:

Five,??? The last cup, we are good friends after it's done [Method area]

The memory area shared by threads is used to store data such as class information, constants, static variables, and code compiled by the just-in-time compiler that have been loaded by the virtual machine.

The method area also does not need contiguous memory and can choose a fixed size or expandable, and you can also choose not to implement garbage collection. Most programmers developed on the HotSpot virtual machine will also call the method area "permanent generation" because garbage collection extends to the method area, but it does not mean that data enters the method area (permanent generation), just like The name "permanent generation" also exists forever, but relatively speaking, garbage collection seldom occurs in this area. The goal of memory recovery in this area is mainly for the recovery of the constant pool and the unloading of the heap type. Generally speaking, the recovery results in this area are more unsatisfactory and may cause memory leaks, but the recovery of this area is still necessary.

When the method area cannot meet the memory allocation requirements, an OutOfMemoryError exception will be thrown .

Runtime constants

The pool is part of the method area. In addition to the description information of the class version, fields, methods, and interfaces in the class file, there is also a constant pool, which is used to store various literal and symbol references generated by the compiler. This part of the content will be entered after the class is loaded Stored in the runtime constant pool where the method goes.

Another important feature of the runtime constant pool compared to the class file constant pool is that it is dynamic. The Java language does not require constants to be generated only by the compiler. New constants can also be placed in the pool during runtime. The feature used by developers is the intern() method of the String class .

Part of the method area of ​​the constant pool at runtime is naturally restricted by the method area. When the constant pool can no longer apply for memory, an OutOfMemoryError exception will be thrown .

After making these five glasses of wine, the picture above becomes the following

At this point, we have finished 5 glasses of wine, presumably a lot of classmates are already on it, it's just right for a little drunk, let it be an interviewer! If the classmates are still a little dizzy, it doesn't matter, let us continue to drink in the future, we must practice your amount, and we are not afraid of any interviewer we encounter in the future.

There are hot recommendations???

Dry goods: A text to understand how client requests reach the server

SpringBoot+Redis distributed lock: simulation of order grabbing

How to choose between Spring Cloud and Dubbo?

Share several ways to stop Spring Boot gracefully, not just kill -9

Dry goods sharing : The official account backstage reply " 99 " to receive 99 sets of actual combat projects + information

Charging want to focus on the process programmer flash charge treasure

If the article is helpful, read it and forward it.

Thank you for your support (*^__^*)

Guess you like

Origin blog.csdn.net/qq_17231297/article/details/106233786