Deep understanding of the Java Virtual Machine-memory management mechanism

Source: Internet
Author: User

As mentioned above, the loading mechanism of the class, which refers to the initialization of the class using a part of memory management knowledge, here let us see how the Java Virtual Machine management memory.

Let's take a look at the picture first.

In some articles, the thread containment zone is also known as the thread exclusive area, which is actually a meaning. Let us introduce the following five parts in detail;

Run-time Data area

The Java virtual machine, in the course of executing a Java program, divides the memory it manages into several different data regions that have their own uses and are built and destroyed as the JVM process starts or the user thread starts and ends.

Let us first understand the difference between the process and the thread:

A process is the smallest unit of resource allocation, and a thread is the smallest unit of program execution.

The process has its own independent address space, and each time a process is started, the system assigns it an address space, establishes a data table to maintain code snippets, stack segments, and data segments, which are expensive to operate. threads, which are data in a shared process, use the same address space, so the CPU switches one thread much less than the process, and the overhead of creating a thread is much smaller than the process.

The same process can include multiple threads, and the thread shares the resources (registers, stacks, contexts) of the entire process, and a process contains at least one thread. Communication between threads is more convenient, threads in the same process share data such as global variables, static variables, and communication between processes needs to be done in a communication way (IPC).

Here is a quote in the understanding of a classmate's explanation,

The granularity of the process is too large, each time to have the top and bottom of the call, save, recall. If we liken the process to a computer-run software, then the execution of a software can not be a logical execution, there must be more than one branch and a number of program segments, like to implement program A, is actually divided into a,b,c, such as a combination of multiple blocks. Then the concrete execution here can become:

Program A gets CPU = "CPU loading context, starts executing program A's a small segment, then executes A's B-segment, then executes the C-segment of a, and finally the CPU holds the context of a."

The execution of A,b,c here is to share the context of a, and the CPU does not have context switching when it executes.

See if this is a deeper understanding of thread sharing and thread containment. It can be understood that the method area and the heap are allocated to the process, that is, the thread share, while the stack and program counters are assigned to each individual thread.

The Java Virtual machine stack and the local method stack are merged in the Sun's hotspot virtual machine

Program counter (Counter Register)

Program Counter Register is a small memory space that can be seen as the line number indicator of the byte code executed by the current thread . In the computer, in fact, the program counter is a register, according to different computer details of the difference, it can hold the command currently being executed, you can also put down a executed instruction.

In the virtual machine conceptual model, the bytecode interpreter works by changing the value of this counter to select the next byte-code instruction to execute .

Because the multithreading of a Java Virtual machine is implemented by thread polling and allocating processor execution time, at any given time, a processor executes only the instructions in one thread, so that it can be restored to the correct execution position after a thread switch. Each thread needs to have a separate program counter, the counters between the threads do not affect each other, independent storage, so the program counter is thread-private memory, that is, it belongs to the thread quarantine.

If the thread executes a Java method, this counter records the virtual machine bytecode instruction address being executed, and if the native method is being executed, then the value of this counter is (Undefined).

This memory area is the only area in the Java Virtual Machine specification that does not stipulate any outofmemoryerror conditions.

Java Virtual Machine stack

The Java Virtual machine stack is also thread-private, i.e. his life cycle and thread are the same.

In Java, the stack in the JVM records the thread's method calls, each of which has a stack, and in the run of a thread, if there is a new method call, the corresponding stack of the thread will add a storage unit, the stack-Frame.

The virtual machine stack describes the memory model that the Java method executes: Each method creates a stack Frame to store information such as local variable tables, operand stacks, dynamic joins, method exits, and so on. each method from the call to completion of the process, corresponding to a stack frame in the virtual machine stack from the stack to the process of the stack.

When the called method finishes running, the corresponding frame of the method is deleted, and the space occupied by the parameter and the local variable is freed. The thread goes back to the original method and continues execution. When all the stacks are emptied, the program also ends with the run.

What we often say about stack memory is actually the virtual machine stack, or the local variable table part of the virtual machine stack.

The local variable table holds the various basic data types known to the compiler (Boolean, Byte, char, short, int, float, long, double), object reference (reference type, which is not equivalent to the object itself, It might be a reference pointer to the start of an object, or it could be a handle to an object or other location related to the object, the object that the reference points to is saved in the heap (the reference may be null, that is, it does not point to any object), and the ReturnAddress type (the address of a bytecode directive).

The 64-bit length of long and double data takes up 2 local variable space (slots), and the remaining data types occupy only 1. The memory space required by the local variable table is allocated at compile time. When entering a method, this method needs to allocate how much local variable space in the frame is fully determined, and the size of the local variable table is not changed during the operation of the method.

There are two types of exceptions

1, the stack depth of the thread request is greater than the allowed depth of the virtual machine will throw Stackoverflowerror exception (recursive call)

2, if the virtual machine can be dynamically extended, the Outofmemeoryerror exception will be thrown if the extension has not been able to request enough memory.

List list=new ArrayList ();        for (;;) {            int[] tmp=new int[1000000];            List.add (TMP);        }

Local method Stack

The local method stack (Native) is very similar to the virtual machine stack. The difference between them is that the Java Virtual machine stack is a bit virtual machine executing Java method (that is, bytecode) service, and the local method stack is a native method service used by the bit virtual machine.

In fact, the virtual machine specification in the local stack method used in the language, usage and data structure are not mandatory, so the specific virtual machine can be free to implement it. Even in some virtual machines, such as sun hotspot virtual machines, the local method stack and the virtual machine stack are directly merged. As with virtual machine stacks, the local method stack area throws Stackoverflowerror and OutOfMemory exceptions. Java heap for most applications, the Java heap (Java heap) is the largest piece of memory managed by the Java Virtual machine. The Java heap is a piece of data that is shared by all threads, created when the virtual machine is started, and the only purpose of this memory area is to hold object instances where almost all object instances allocate memory. but with the development of JIT compiler and escape analysis technology matures, stack allocation, scalar replacement optimization technology will lead to some subtle changes occur, all objects are allocated on the heap and gradually become less "absolute"。 The heap can be subdivided into the new generation and the old age, in the subdivision can be divided into Eden Space, Form survivor space, to survivor space. The Java heap is the main area of garbage collector management, so it is often referred to as the "GC heap". According to the Java Virtual Machine specification, the Java heap can be in physically discontinuous memory, as long as it is logically contiguous, just like our disk space. When implemented, can be fixed size is also extensible. Mainstream virtual machines are implemented in a scalable way (controlled by-XMX and-XMS). A Outofmemorterror exception is thrown if there is no memory to allocate in the heap and the heap cannot continue to expand.

Java's normal objects exist in the heap, unlike stacks where the heap's space is not emptied as the method call ends. Therefore, objects created in a method can continue to exist in the heap after the method call ends. One problem with this is that if we constantly create new objects, the memory controls will eventually be exhausted.

Method area

The method area, like the Java heap, is an area of memory shared by each thread that stores data such as class information, constants, static variables, and code that is compiled by the instant compiler, which have been loaded by the virtual machine . Although the Java virtual machine describes it as a logical part of the heap, it has an alias called Non-heap (Not a heap). The purpose is to differentiate it from the Java heap. (many people previously called the method area a permanent generation, and now the JDK1.8 has replaced the permanent generation with the metadata region).

Run a constant-rate pool

The runtime Constant pool is part of the method area. In addition to the class file, which has a description of the version, field, method, interface, and so on, there is a constant pool of information. Used to hold the various literal and symbolic references generated by the compilation period, which are stored in the run-time pool that the class loads into the method area. It is not the content of the constant pool that is pre-placed in the class file to enter the method run-time pool, which may also put new constants into the pool during the run, which is the intern () method of the string class used by developers.

public class test{public    static void Main (string[] args)    {        String s1= ' Hello China ';//byte-code constant        String s2= " Hello China ";        String S3=new string ("Hello China");        System.out.println (S1 = = s2);        System.out.println (S1 = = S3);        System.out.println (S1 = = S3.intern ());//run-time constant  intern is a native method    }}

Thrown OutOfMemoryError when the method area does not meet the memory allocation requirements

Note: Before JDK8, the method area is implemented by the permanent generation, the main storage class information, Chang, method data, method code and so on; After JDK8, the permanent generation is removed, the meta-space is moved, and the constant pool, static member variables are migrated to the heap, and the meta-space is not in the virtual machine memory but in local memory.

Direct Memory

Because direct memory is not part of the data area of the Java Virtual Machine runtime, nor is it defined in the Java VM specification, this part is also used frequently and can cause memory overflow anomalies to occur, so it is also introduced in this section.

First, the allocation of native direct memory is not limited by the size of the Java heap, but must still be limited by the size of the native total memory and the processor addressing space. When the administrator configures the virtual machine parameters, the parameter information such as-XMX is set according to the actual memory, but the direct memory is often ignored, causing the sum of each memory region to be greater than the physical memory limit (including physical and operating system-level limitations), resulting in OutOfMemoryError exceptions when dynamically expanding.

JDK1.4 joins NiO and introduces a channel-to-buffer-based I/O method that allocates out-of-heap memory using the native library and then operates through a Directbytebuffer object stored in the Java heap as a reference to that memory. This avoids replicating data back and forth in the Java heap and the native heap, improving performance.

Object obj = new Object ();

Object obj will be reflected in the virtual machine stack (reference type)
The new Object () will be reflected in the Java heap
Such information data as the object type, parent class, implemented interface, method, and so on, will be reflected in the method area

Deep understanding of the Java Virtual Machine-memory management mechanism

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.