Deep understanding of JVM memory areas and memory allocation in JVM, and deep understanding of jvm

Source: Internet
Author: User

Deep understanding of JVM memory areas and memory allocation in JVM, and deep understanding of jvm

The following are basically not original, and they are all reprinted.

 

When JVM is running, you must firstClassLoader)Load the bytecode of the required class and submit itExecution engineExecution, the execution process requires a space to store data (analogyCPU and primary memory). The process of allocating and releasing memory space is what we care about.Runtime data Zone.

Runtime data Zone

As shown in, the runtime data zone includes:Program counters(PC register ),Java Virtual Machine Stack(VM Stack ),Java heap(Heap ),Method Area(Method Area ),Local method Stack(Native Method Stack ). Next we will give you a deep understanding of eachData Region.

JVM is actuallyVirtual ComputerTo achieve"One compilation, executed everywhere". Therefore, when you understand the runtime data zone, you canOperating system memory, registersAnalogy learning.

2.2.1 program counter

The program counter is a small memory area, which can be regarded as the position indicator of the bytecode executed by the current thread. This calculator is required for basic functions such as branch, loop, jump, exception handling, and thread recovery.

Note: The program counter in the Java Virtual Machine points to the address of the bytecode being executed, rather than the next one.

Each thread has an independent counter to ensure that the thread switches back to the correct position. Therefore, the memory area of the program counter is thread isolated. This region is the only region that does not specify any OutOfMemoryError.

2.2.2 Java Virtual Machine stack (VM Strack)

The Virtual Machine stack is also called the stack memory. It is created when the online process is created and the thread is private. Its life cycle is the life cycle of the following thread, and the stack memory is released when the thread ends, there is no garbage collection problem for the stack. As long as the thread ends, the stack will be Over, so there is no garbage collection. Some materials are also translated into JAVA method stack, probably because it describes the Memory Model of java method execution.

Create a Frame Stack (Strack Frame) for each method execution to store the local variable table (including the corresponding method parameters and local variables), the Operation Stack (Operand Stack, records stack and inbound operations), dynamic links, method exits, and other information. Each method is called until the execution is complete, corresponding to the process of the stack in the VM stack and the process of the stack.

 

Stack frame is a memory block, a data set, and a data set related to Method and runtime data. Let's take a look at a figure to understand the Java stack and follow"Advanced and later"Principle. As shown in:

 

Most people refer to stack memory as part of the local variable table in the VM stack.

The local variable table stores various basic data types (boolean, byte, char, short, int, float, long, and double) that are known during the compilation period, and references of objects (reference type, unlike the object itself, different virtual machine implementations may be a reference pointer pointing to the starting address of the object, or a handle representing the object or other locations related to the object) and returnAdress (pointing to the address of the next bytecode command ). The memory space required by the local variable table is allocated during compilation. Before the method is run, the memory space required by the local variable table is fixed and will not change during running.

Exception

2.2.3 local method stack (Native Method Stack)

1. The local method stack is similar to the Virtual Machine stack. The difference is that the Java method (also known as bytecode) executed by the Virtual Machine stack record, while the local method stack recordsNativeMethod.

2. Combine the local method stack and Virtual Machine stack into one in the HotSpot virtual machine.

3. The local method stack will also throwStackOverflowErrorAndOutOfMemoryErrorException.

2.2.4 Java Heap)

1. the Java heap is a memory area shared by all threads. It is created when the VM is started.

2. The largest piece of memory managed by JVM. Almost all object instances and arrays are stacked, and the member variables of the class are also stacked. (A single member variable of a class refers to the reference of a basic variable ?? I have not made any corrections yet)

3/The Java heap can be in physically discontinuous memory space, as long as the logic is continuous, just like our disk space.

Memory Model

This area is the main area for managing the Garbage Collector ("GC Heap "). At present, the collectors basically use the generational collection algorithm: The New Generation adopts the replication algorithm, and the old generation adopts the mark cleaning algorithm. From the perspective of memory collection, Java heap can be dividedNew Generation(Young Generation) andOld Generation(Old Generation ). This Division aims to better recycle the memory (the old generation memory will be preferentially recycled ).

The new generation can also be dividedEden Space,From region vor Space,To allocate vor Space.

Permanent generation(Permanent Generation) for storageStatic Data, Has little to do with the garbage collector.

Note:: This figure showsJVM Heap Memory Model, JVM heap memory includesJava heap AreaAndPermanent Region. Therefore,Permanent generation does not belong to Java heap.

Exception

Same Java heapScalable(-Xmx and-Xms parameters ). If the heap memory cannot be allocated to the object instance and cannot be expandedOutOfMemoryErrorException.

 

2.2.5 Method Area (Method Area)

The method area is also called permanent generation. In the past (when the custom class loader is not very common), most classes were static and rarely uninstalled or collected, therefore, it is called "Permanent )".

It is also called Non-Heap (Non-Heap), a memory area shared by all threads. It is used to store information about classes loaded by virtual machines (Object Class Data (loading Class definition Data of a Class)), Constants, static variables, real-time Compiler (JIT) compiled code, and other data.

The method area can also be composed of areas with Discontinuous memory, and can be set to a fixed size or scalable, which is the same as the heap.

Garbage collection will rarely appear in this region. The purpose of memory collection in this region is mainly to recycle the constant pool and unload the class (which will be mentioned later ).

  2.2.6 runtime constant pool(Runtime Constant Pool)The runtime constant pool is part of the method area. In the bytecode file (Class file), in addition to the Class version, fields, methods, interfaces, and other information descriptions, there are also Constant Pool Table information, it is used to store the literal volume and symbolic reference generated by the compiler. After the class is loaded, this part of content will be stored in the rcp in the method area. It is worth noting that another important feature of the runtime constant pool relative to the CLass file constant pool is dynamic, so the new constants generated during runtime can also be placed in the constant pool, for example, the constant generated by the intern () method in the String class.
package intern;public class Main1 {    public static void main(String[] args) {        String s0= "I'm coding";           String s1=new String("I'm coding");           String s2=new String("I'm coding");           System.out.println( s0==s1 );          System.out.println( s0==s1.intern());           s2=s2.intern();          System.out.println( s0==s2 );                 }}

Output result

falsetruetrue

In this example, s0 is saved inConstant pool, S1 and s2 object instances are stored inJava heap. = Directly compare objectsHashCodeTherefore, the first line of outputFalse. The s1.intern () method returns the reference of s1 in the constant pool. If no value exists, it is created.
The string stored in s1 already exists in the constant pool. The s0 reference is directly returned, and the second row is output.True.
LikewiseS2 receives the return value of s2.intern (). The string value is the same as that of s0, and the output of the third line isTrue.

The constant pool is an ordered set of constants used for this type. Including Direct constant (basic type, String)And Symbol reference for other types, methods, and fields. For example:◆ Full-qualified names of classes and interfaces; ◆ field names and descriptors; ◆ methods and names and descriptors. The data in the pool is accessed through indexes like the array. Because the constant pool contains all types of symbolic references to other types, methods, and fields, the constant pool plays a core role in the dynamic link of Java. very useful and important about the constant pool Extension: Java constant pool detailed http://www.cnblogs.com/DreamSea/archive/2011/11/20/2256396.html runtime constant pool is part of the method area, so by the method Area Memory limit. When the memory cannot be applied OutOfMemoryErrorException. 2.2.7 Direct Memory

The direct memory area is not a part of the memory area managed by the JVM, but outside of it. This area will also be used in Java Development and may cause memory overflow. If you have some knowledge about NIO, it may be known that NIO can use Native Methods to use the Direct Memory zone.

The NIO class is added to JDK 1.4 and an I/O Method Based on Channel and Buffer is introduced. It can be used to directly allocate off-heap memory using the Native function library, then, use a DirectByteBuffer object stored in the Java heap as a reference to the memory. This can significantly improve the performance in some scenarios, because it avoids repeated data replication in the Java and Native stacks.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.