Hello, I am Bao Brother, following the article, we talked about

The process by which the JVM loads a class

Some interviewers will ask you to explain the Java memory model. Some of them get it right, but the interviewer will say no, it should be heap, stack, method area, etc.

By the end of this article you will know:

  • 1.JVM memory structure
  • 2.JVM stack frame analysis
  • 3. The difference between method areas in JDK1.7 and 1.8
  • 4. Generation structure of heap

Suggest collection!

JVM memory structure

First, the JVM memory structure and the JAVA memory model are two different concepts.

JVM memory structure:

Class files are loaded into memory via the Class loading mechanism. The JVM memory structure is the memory space shown in the figure above. The Java memory model is another concept.

According to the Java Virtual Machine Specification (Java SE 7 Edition), the following figure shows the memory managed by the Java VIRTUAL Machine.

As can be seen from the figure above, the runtime data is divided intoThe five regions. These areas each have their own uses, of which the method area and heap are allThreads share, stack, local method stack and program counter areThread private.

1. Program counter

A program counter is a small memory space that is private to the thread and can be considered a line number indicator for the current thread.

Why program counters

Because the CPU will switch context between multiple threads, you need to use the program counter to track which line the current thread is running on, and wait for the thread to retrieve the running time and continue to execute from the count position. It is thread-private because each thread counts independently and there is no effect between threads.

Interview question: Do outofMemoryErrors occur with program counters?

A: This memory region is the only one in the virtual machine specification that does not have OutofMemoryErrors. If the thread is executing a Java method, the counter records the address of the virtual machine bytecode instruction. If the method is native, the counter is empty.

2.Java stack (JVM thread stack)

The first thing to remember is that the stack describes the in-memory model of method execution, which is thread-private.

When each method is executed, a stack frame is created to store information about local variables, action stacks, dynamic links, method exits, and so on. Each method called corresponds to a stack frame in the virtual machine stack from the stack to the stack, as shown in the following figure:

Interview question: What are two types of exceptions that can occur in the Java virtual machine stack?

  • The virtual stack is a stack, and when our stack frame exceeds the maximum depth, a StackOverflowError is thrown
  • OutOfMemoryError is thrown if the stack cannot obtain sufficient space

The Stack Frame (Stack Frame)

The process of each method from invocation to completion of execution corresponds to the process of a stack frame in the virtual machine stack from stack to stack, so what does a stack frame contain?

  • Local Variable Table

Also called the local variables, it needed to complete assigned at compile time, memory space when entering a method, this method need to be allocated in the stack is entirely sure how local variable space, the method does not change during operation, it is the smallest unit of Slot, one Slot can be stored within a 32-bit data types. The VM searches for local variables by indexing them. The index ranges from 0 to the maximum capacity of the table. If Slot is 32-bit, a variable of 64-bit data type (such as long or double) is encountered, and two consecutive slots are used to store it

  • Operand Stack

Also known as an operation stack, it is a LIFO stack. When a method just starts, its operand stack is empty, as the method of execution and bytecode instruction execution, from local variables or object instances in the field of reproduction constant or variable written to the operand stack, again with the calculation of the elements in the stack to the local variables or method is returned to the caller, that is out of/into the stack operation. A complete method execution usually consists of several such out/on/off processes.

  • Dynamic Linking

In a class file, for a method to call other methods, symbolic references to those methods need to be converted into direct references to their memory addresses, and symbolic references exist in the run-time constant pool in the method area. In the Java virtual machine stack, each stack frame contains a symbolic reference to the method that the stack belongs to in the runtime constant pool. This reference is held to support Dynamic Linking during method invocation. Some of these symbolic references are converted directly to direct references during class loading or the first time they are used, which is called static resolution. The other part is converted to a direct reference during each run, which is called a dynamic join.

  • Method Return address

When a normal method executes, there are two ways to exit the method

  • 1.The normal exitNormal exit means that the method completes normally and exits without throwing any exceptions. If the current method completes normally, a return value may be passed to the method caller based on the bytecode instructions returned by the current method(Calling its methods), or no return value(void). Whether there is a return value and the data type of the return value are determined based on the bytecode instructions returned by the method.
  • 2.Abnormal exitAn exception encountered during the execution of a method, which is not handled within the method body, will cause the method to exit. If no corresponding exception handler is found in the exception table of the method, the method will exit.

The method exit process is essentially the same as removing the current stack frame from the stack, so exit can perform operations such as restoring the local variable table and operand stack of the upper method, pushing the return value (if any) into the caller’s operand stack, and adjusting the PC counter value to point to the next instruction after the method call instruction. In general, when a method exits normally, the caller’s PC count can be used as the return address and may be stored in the stack frame. When the method exits abnormally, the return address is determined by the exception handler table, and this part of information is generally not stored in the stack frame

  • Additional information

This refers to the addition of information to the stack frame in the virtual machine implementation that is not described in the specification, such as debugging information.

Local method stack

Local method and the virtual machine is stack is very similar to the role of, the difference is a Java virtual machine stack are executable method (i.e. bytecode) service, while the local method stack service for virtual machine to use native methods, may be the underlying call c or c + +, we open the JDK installation directory can see there are a lot of files written in c, Probably the C code that native methods call.

Java is a cross-platform language. Since it is cross-platform, the cost is to sacrifice some control of the bottom layer. To realize the control of the bottom layer, Java needs the help of some other languages, which is the role of Native.

The heap

It is shared by all threads and its purpose is to hold object instances. It is also the main area managed by the GC, so it is often referred to as the GC heap. Now the collector often uses generational algorithms for garbage collection, and this is where the garbage collection is most concentrated.

Heap generation structure

The heap is divided into two distinct regions: Young and Old.

Young is divided into three regions: Eden, From Survivor, and To Survivor. Their default proportions are shown below:

  • Young Generation

The newly generated objects are preferentially stored in the new generation, and the new generation objects die overnight, with a very low survival rate. In the new generation, the conventional application of a garbage collection can generally recover 70% to 95% of the space, and the recycling efficiency is very high

  • Survivor zone there are two Survivor zones: From Survivor zone, To Survivor zone, also known as S0 zone,S1 zone. During GC, all surviving objects in Eden will be copied To To Survivor. In FromSurvivor, the surviving objects will go where they are based on their age, which reaches an age threshold (default: 15). Every time a new generation of objects survives a garbage collection cycle, The age value is incremented by 1, GC generational ages are stored in the header of the object), and objects that do not reach the threshold are copied To Survivor. Then clear the Eden zone and From Survivor zone. All the surviving objects of the new generation are in the To Survivor zone. Then, the From and To Survivor zones swap roles, and GC relies on the old generation for allocation guarantees when the To Survivor zone does not have enough space To store surviving objects collected by the previous generation.

  • Old age (Old)

Objects that survive multiple GCS in the new generation (depending on the value of the virtual machine configuration) will enter the old generation. The life cycle of objects in the old age is longer, the survival rate is higher, the frequency of GC in the old age is relatively low, and the recovery speed is slower


Often meet try:

  • When does a Minor /Young GC occur?

Newly generated objects are allocated in Eden (except for large objects, which go directly to the old age). When Eden does not have enough space to allocate objects, the virtual machine initiates a Minor GC, also called a Young GC

  • Why generation? Objects are classified according to survival probability, and objects with long survival time are placed in a fixed area to reduce garbage scanning time and GC frequency. Different garbage collection algorithms for classification are carried out to maximize the advantages and avoid the disadvantages of the algorithm

Methods area

The main differences between JDK1.8 and JDK1.7 are as follows:Metaspatial regions replace permanent generationsPermanent generation is the main storageClassandMetaThe information. The essence of a meta-space, like a permanent generation, is an implementation of the method area in the JVM specification. But the biggest difference between a metaclspace and a permanent generation is this:The meta-space is not in the virtual machine, but uses local memory. Therefore, by default, the size of the meta-space is limited only by local memory.

As you can see in the figure above,JDK1.7 and 1.8 have made adjustments to both the runtime data area and the method area in the heap, and a new memory area called Metaspace has been introduced in JDK8. Not all JVMS have permanents. IBM’s J9 and Oracle’s JRocket do not have permanents. Permanents are implementation-level things, and the contents of permanents are basically those specified in the method area.


Interview question: The difference between method area, permanent generation and meta-space?

  • Methods area: is the JVM specification that all virtual machines must follow. Is shared by all threads of the JVM to store class information, constant pools, method data, method code, and so on.
  • The permanent generation: Full name Permanent Generation space: a Permanent memory storage area. It’s the HotSpot VIRTUAL machineBased on the JVM specificationA landing implementation of the method area, and only HotSpot has PermGen space, was removed in JDK8.
  • dimension: The biggest difference between a meta-space and a permanent generation is that the meta-space is not in a virtual machine, but uses local memory. It is alsoBased on the JVM specificationA landing implementation of the method area

In JDK6 and JDK7, the method area is PermGen. In JDK8, the method area is Metaspace

Examples of heap overflows in different JDK versions:


Interview question: Why are permanent generations removed?

1) String exists in permanent generation, which is prone to performance problems and memory overflow.

2) It is difficult to determine the size of information about classes and methods, so it is difficult to specify the size of permanent generation. If the size is too small, it is easy to overflow the permanent generation, while if the size is too large, it is easy to overflow the old generation.

3) Persistent generation brings unnecessary complexity to GC and low collection efficiency.

conclusion

Now that we know how the JVM manages memory and its structure,

Don’t confuse the JVM runtime data area with the JMM(Java Memory Modle)

JAVA object layouts are different concepts as I mentioned in one of my articles

In the next article we’ll look at the JMM(Java’s memory model) and escape analysis in Java, as well as multithreaded programming extensions. Please continue to pay attention to the public number :JAVA Baodian

Welcome to pay attention to the public number: Java treasure to receive more tutorial welfare