Deep understanding of JVM memory area and memory allocation

Source: Internet
Author: User

when studying the memory allocations of the JVM, the blog read this blog, which summarizes the memory allocations of the JVM, and also uses the JVM's memory model to explain questions about parameter passing in a Java program.

Blog Source: http://www.cnblogs.com/hellocsl/p/3969768.html?utm_source=tuicool&utm_medium=referral

After reading this blog, I found that we should go deep into the memory model of the JVM, that is, to seriously study the "deep understanding of Java Virtual Machine", its content may be "deep Exploration of C + + object Model" similar, explaining the object in Java in memory model, after learning the object's memory model, to understand polymorphism, The understanding of parameter passing, etc. is helpful.

Preface: This is an article about the memory area of the JVM, from the online some articles about this and "in-depth understanding of Java Virtual Machine" collation, so there will be some similarities, there is no guarantee that I write more than other online and books on the better, it is impossible to do so. The purpose of blogging is to personally understand this aspect of the sharing and personal accumulation, so there is a lot of mistakes in the advice.

See in depth two words, believe that a lot of Java beginners will directly ignore this article, in fact, the knowledge of the memory area of the JVM is very important for beginners, understand the principle of Java memory allocation, which will have a deeper understanding of Java learning, this is my personal view.

Let's take a look at the memory area of the JVM runtime

Most JVMs divide the memory area into method Area (non-heap), Heap(heap),program Counter Register (procedure counter) , VM Stack (virtual machine stack, also translated into Java method stack), Native method Stack ( local method Stack ), where method area and Heap are thread-shared , VMstack,native method Stack and Program Counter Register is non-thread-shared. Why is it divided into thread sharing and non-thread sharing? Please continue looking down.

First, we are familiar with the working process of a generic Java program. A Java source program file will be compiled into a bytecode file (with class extension), each Java program needs to run on its own JVM, and then inform the JVM program run the portal, and then by the JVM through the bytecode interpreter load run. So how does the program get involved in each memory area after it starts running?

In summary, the JVM allocates the method area and Heap (heap)when it is initially run, and the JVM assigns a program Counter each time it encounters a thread. Register (program counter), VM stack (virtual machine stack) and native method stack (local stack), when thread terminates, three (virtual machine stack, The memory space occupied by the local method stack and the program counter is also freed. This is why I divide the memory area into thread sharing and non-thread sharing, and the three areas of non-thread sharing have the same life cycle as the owning thread, while the areas shared by the threads are the same as the Java program's life cycle. So this is where the system garbage collection takes place only in the area of the thread share (which is actually known to the heap on most virtual machines).

  

1. Program counter

A program counter is a small area of memory that can be seen as a positional indicator of the bytecode that is being executed by the current thread. Basic functions such as branching, looping, jumping, exception handling, and thread recovery all need to rely on this calculator to do it, not much.

2.VM Strack

Let's start by understanding the composition of the following Java directives:

A Java instruction consists of an opcode (the method itself) and an operand (method internal variable).    

1) The method itself is the operation code part of the instruction, which is stored in the stack;2) The method internal variable (local variable) as the operand part of the instruction, followed by the instruction opcode, saved in the stack (actually a simple type (int,byte,short, etc.) saved in the stack, Object type save address in stack, save value in heap);

The virtual machine Stack is also called the stack memory, is created when the thread is created, its life is to follow the threads of Life , thread end stack memory is released, there is no garbage collection problem for the stack, as long as the end of the thread, the stack is Over, so there is no garbage collection . There is also some data translated into the Java method stack, presumably because it describes the memory model that the Java method executes, and each method executes while creating the frame stack (Strack frame) for storing the local variable table (which contains the corresponding method parameters and local variables). The Operation Stack (Operand stack, record stack, stack operation), dynamic link, method exit and other information, each method is called until the completion of the process, corresponding to the frame stack in the virtual machine stack in the stack and the process of the stack.

The local variable table holds the various basic data types (Boolean, Byte, char, short, int, float, long, double) that are known at compile time, and the object's reference (reference type, which is not equivalent to the object itself and is implemented according to different virtual machines. May be a reference pointer to the start address of the object, or it may be a handle to the object or other object-related location, and the returnadress type (the address of the next bytecode Directive). The memory space required for the local variable table is allocated during compilation, and the local variable table requires a fixed amount of memory before the method is run and does not change during the run time.

Stack frame is a memory block, is a data set, is a method and run-time data set , when a method A is called to produce a stack frame F1, and is pressed into the stack, a method called the B method, resulting in a stack frame F2 is also pressed into the stack, after execution, the first pop-up F2 stack frame, and then pop up the F1 stack frame, follow the " advanced after out " principle. Light says it's boring, let's look at a diagram to understand the Java stack, as shown in:

3.Heap

The heap is the memory data area of the JVM. Heap management is complex and is an area of memory shared by all threads, created at the start of the JVM, dedicated to saving instances of objects. Allocating a certain amount of memory in the heap to hold an object instance is actually just the property value of the object instance, the type of the property and the type tag of the object itself, not the method of saving the object (which is stored in the stack as a frame stack), and allocating a certain memory-saving object instance in the heap. When an object instance is allocated in the heap, a 4-byte heap memory address is stored in the stack, which locates the object instance in the heap, facilitates locating the object instance, and is the primary place for garbage collection. The Java heap is in a physically discontinuous memory space, as long as it is logically contiguous.

4.Method Area

The Object class data (the class definition of the load Class) is stored in the method area. In addition, the compiled code for constants , static variables , and JIT (Instant compilers) is also in the method area. Because the data stored by the method area has an analogy with the heap, it is also called Non-heap. The method area can also be a contiguous area of memory, and can be set to a fixed size or extensible, as is the case with heaps. garbage collection is less likely to occur in this area, and the purpose of this area of memory reclamation is primarily for the collection of constant pools and unloading of classes. 5. Run a constant pool (runtime Constant)within the method area, there is a very important area, called the run-time pool (runtime Constant pool, referred to as RCP). In a bytecode file (class file), in addition to the class version, field, method, interface, and so on, there is a Chang (Constant Pool Table) information that stores the literal and symbolic references produced by the compiler. This section is stored in the RCP in the method area after the class is loaded. It is important to note that the new constants produced by the runtime can also be put into constant pools, such as constants produced by The Intern () method in the String class. A constant pool is an ordered set of constants used by this type. Includes Direct constants (basic types, String) and symbolic references to other types, methods, and fields. For example: The fully qualified name of the class and interface, the name and descriptor of the field, the method and the name, and the descriptor. The data in the pool is accessed through the same index as the array. Because a constant pool contains symbolic references to other types, methods, and fields for one type, Chang plays a central role in the dynamic linking of Java.useful and important extensions to the constant pool: Java constant pool details http://www.cnblogs.com/DreamSea/archive/2011/11/20/2256396.html 6.Native Method Stack   Similar to VM Strack, VM Strack provides a service for the JVM to execute Java methods, and Native method stack provides the JVM with a service that uses Native methods. 7. Direct Memory AreaThe direct memory area is not part of the memory area managed by the JVM, but is outside of it. The region is also used in Java development, and there are pitfalls that cause memory overruns. If you know about NIO, you might know that NiO can use Native Methods to use the direct memory area. Summary:
    • Here, you have a certain understanding of the memory area of the JVM, the JVM memory area can be divided into two parts: thread sharing and non-thread sharing, thread sharing has heap and method area, non-thread sharing has virtual machine stack, local method stack and program counter.

8.JVM Operating Principle Example

All of this is purely theoretical, let's give an example of how the JVM works, let's write a simple class with the following code:
1 public class Jvmshowcase {   2//Static class constant,   3 public final static String class_const = "I ' m a CONST";   4//Private instance variable   5 private int instancevar=15;   6 public static void main (string[] args) {   7//Call static method   8 Runstaticmethod ();   9//Call non-static method  Jvmshowcase showcase=new jvmshowcase ();  Showcase.runnonstaticmethod (+);  13}  //General static method  , public static String Runstaticmethod () {  class_const;  17//Non-static method public  int runnonstaticmethod (int parameter) {int  Methodvar=this.instancevar * parameter;  return Methodvar;  22}  
This class doesn't make any sense, don't guess what the class is doing, just write a more typical class, and then we'll look at how the JVM works, that is, after entering Java jvmshow, let's see how the JVM is handled: 1th Step , Request free memory to the operating system. The JVM said to the operating system, "Give me 64M (random simulation data, not real data) free memory", so the JVM to the operating system to request free memory for the system to find its own memory allocation table, find a segment of 64M memory write "Java occupy" label, and then the memory segment of the starting address and the terminating address to JVM,JVM ready to load the class file. 2nd step, allocates memory memory. The JVM allocates memory. When the JVM gets to 64M of memory, it begins to get a memory, and then allocates the heap memory. 3rd Step, the file examines and parses the class file. Returns an error if an error is found. 4th step, loads the class. Loads the class. Because the loader is not specified, the JVM uses the bootstrap loader by default and loads all classes under Rt.jar into the heap-stored method area,jvmshow is also loaded into memory. Let's look at the method area, such as: ( This time contains symbolic references to the main method and the Runstaticmethod method, because they are static methods that are loaded when the class loadsThe Heap is empty, and the Stack is empty because there are no new objects and threads being executed. 5th step, execution method. Executes the main method. Execution starts a thread, starts executing the main method, and before main executes, the method area is as follows: ( Public final static String class_const = "I ' m a CONST"; The Class_const constant is added to the method area, which is generated the first time it is accessed (inside the Runstaticmethod method).  There are two objects in heap memory, object and showcase objects, as shown in: (Performed jvmshowcase showcase=new jvmshowcase (); Why do you have object objects? is because it is the parent of Jvmshowcase, the JVM initializes the parent class first, and then initialize the subclass, no one can initialize the number of parent classes. There are three stack frames in the stack memory, as shown in: At the same time, a program counter is created to point to the next statement to execute. 6th step,Frees memory. Frees memory. At the end of the run, the JVM sends a message to the operating system saying "memory is out, I'll give it to you" and run the end. -------------------------------------------------------------------------------------------- now look at how the JVM memory is allocated, which is reproduced from http://blog.csdn.net/shimiso/article/details/8595564

Pre-Knowledge:

1. A Java file, as long as there is a main entry method, we think this is a Java program, can be compiled and run separately.

2. Whether it is a variable of a normal type or a variable of a reference type (commonly known as an instance), it can be used as a local variable, and they can all appear in the stack. Only the normal type of variable in the stack directly save its corresponding value, and the reference type of the variable is a pointer to the heap area, through this pointer, you can find this instance in the heap corresponding to the object. As a result, a normal type variable occupies only one chunk of memory in the stack, whereas a reference type variable takes up a chunk of memory in the stack area and the heap area.

Example: (in all of the following instances, the stack memory frame stack is simplified to a local variable table as needed, actually by the introduction of the upper-facing frame stack knowing that not only this information, but also the same heap memory)

1.the JVM automatically looks for the main method, executes the first sentence, creates an instance of the test class, allocates a chunk of memory on the stack, and holds a pointer to the heap area object 110925.

2. Create a variable of type int date, because it is the base type, the value of date corresponding to 9 is stored directly in the stack.

3. Create two instances of the Birthdate class D1, D2, each holding the corresponding pointers to their respective objects in the stack. They invoke a constructor with arguments when they are instantiated, so there is a custom initial value in the object.

Call the Change1 method of the test object, and use date as the argument. When the JVM reads this code, it detects that I is a local variable, so I put I in the stack and assigns the value of date to I.

Assign 1234 to I. A very simple step.

The Change1 method executes and immediately releases the stack space occupied by the local variable i.


Call the Change2 method of the test object, D1 the instance as a parameter. The JVM detects that the B parameter in the Change2 method is a local variable, is immediately added to the stack, and because it is a variable of the reference type, B holds a pointer in D1, where B and D1 point to the object in the same heap. Passing between B and D1 is a pointer.


A Birthdate object is instantiated in the Change2 method and assigned to B. The internal execution process is a new object in the heap area, and a pointer to the object is saved to the B corresponding space in the stack, and instance B no longer points to the object that the instance D1 points to, but the object pointed to by instance D1 has no change, so it cannot have any effect on D1.

The Change2 method executes and immediately releases the stack space occupied by the local reference variable B, noting that only the stack space is freed and the heap space waits for automatic recycling.

Call the Change3 method of the test instance, D2 the instance as a parameter. Similarly, the JVM allocates space in the stack for the local reference variable B, and holds the pointer in D2 in B, where D2 and B point at the same object. Invoking the Setday method of instance B is actually the Setday method of invoking the object that D2 points to.

Invoking the Setday method of instance B affects D2 because they point to the same object.

Immediately after the Change3 method is executed, the local reference variable B is released.

These are the general scenarios in which the Java program runs memory allocations. In fact, there is nothing to master the thought is very simple. There are two types of variables: the base type and the reference type. Both as local variables, are placed in the stack, the base type directly in the stack to save the value, reference type only holds a pointer to the heap area, the real object in the heap. As a parameter, the base type is passed directly to the value, and the reference type passes the pointer.

Summary:

1. distinguish what an instance is and what an object is. Class a= New Class (), at which point A is called an instance, not a is an object. The instance is in the stack, the object is in the heap, and the operation instance is actually manipulating the object indirectly through the pointer of the instance. Multiple instances can point to the same object.

2. data in the stack is not synchronized with data destruction in the heap. Once the method ends, the local variables in the stack are destroyed immediately, but the objects in the heap are not necessarily destroyed. Because there may be other variables that point to this object, it is destroyed only if there are no variables in the stack that point to the object in the heap, and it is not destroyed immediately, and can be destroyed when the garbage collection is scanned.

3. The above stacks, heaps, code snippets, data segments, and so on are all relative to the application. Each application corresponds to a unique instance of the JVM, and each JVM instance has its own area of memory that does not affect each other. And these memory areas are shared by all threads. The stacks and heaps mentioned here are concepts on the whole, and these stacks can be subdivided.

4. the member variables of a class vary in different objects and have their own storage space (the member variable is in the object in the heap). The method of the class is shared by all objects of the class, only one set, the method is pressed into the stack when the object is used, and the method does not consume memory.

Deep understanding of JVM memory area and memory allocation

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.