Java Program Runtime memory allocation detailed _java

Source: Internet
Author: User
Tags advantage

I. Basic CONCEPTS

Each Java program runs a Java process, each Java process may contain one or more threads, each Java process corresponds to a single JVM instance, each JVM instance uniquely corresponds to a heap, each thread has its own private stack. All instances of the classes created by the process (that is, objects) or arrays (referring to the array itself, not the reference) are placed in the heap and shared by all threads of the process. The allocation heap memory in Java is automatically initialized, that is, when allocating memory for an object, the variables in the object are initialized. Although the storage space for all objects in Java is allocated in the heap, the reference to this object is allocated on the stack, i.e. allocating memory in the heap and stack when an object is created, and the memory allocated in the heap actually holds the object itself. The memory allocated in the stack is just a reference to the heap object. When the local variable is new, it allocates space in the stack space and the heap space, and when the local variable life cycle is over, the stack space is immediately reclaimed and the heap space area waits for GC to recycle.

The specific concept: the memory of the JVM can be divided into 3 areas: heap (heap), stack (stack), and method area (methods, also known as static regions):

Heap Area:

1. The storage is all objects, each object contains a corresponding class of information (class is to get instructions);
2.JVM has only one heap area (heap) and is shared by all threads, and the base type and object reference are not stored in the heap, only the object itself and the array itself;

Stack area:
1. Each thread contains a stack area in which only the underlying data type itself and the custom object's reference are saved;
2. The data in each stack (original type and object reference) are private and other stacks are inaccessible;
3. The stack is divided into 3 parts: Basic type variable area, execution environment context, Operation instruction area (store operation instruction);

Method area (static area):
1. is shared by all threads, the method area contains all the class (class refers to the original code of classes, to create a class object, the first thing to load the class code into the method area, and initialize) and static variables.
2. The method area contains all elements that are always unique throughout the program, such as class,static variables.

Second, the example demonstration

Appmain.java

public class Appmain   //runtime, the JVM puts all Appmain code in the method area  
{public  
static void Main (string[] args)//main Method itself into the method area.  
{  
Sample test1 = new sample ("Test 1"); Test1 is a reference, so put it in the stack area, sample is the custom object should be placed inside the heap  
sample test2 = new sample ("Test 2");  
 
Test1.printname ();  
Test2.printname ();  
}  
 
public class Sample  //runtime, the JVM puts the Appmain information in the method area  
{  
/** instance name/  
private String name;//new Sample example, The name reference is placed in the stack, and the String object corresponding to name is placed in the heap  
 
./** Construction Method  
/Public Sample (String name)  
{this  
. Name = name;  
 
/** output/public  
void Printname ()//In the absence of an object, the Print method follows the sample class into the method area.  
{  
System.out.println (name);  
}  
}

When you run the program, start a Java Virtual machine process first, This process first finds the Appmain.class file in the classpath, reads the binary data in the file, and then stores the class information of the Appmain class in the method area of the Run-time data area, which is the Appmain class loading process.

The Java virtual machine then navigates to the byte code of the Main () method of the Appmain class in the method area, and begins executing its instructions. The first statement of this main () method is:

Copy Code code as follows:

Sample Test1=new sample ("Test 1");

The execution procedure for this statement:
1, Java Virtual machine to the method area to find the type of sample class information, not found because the sample class has not yet been loaded into the method area (as you can see, the inner classes in Java exist alone and will not be loaded with the containing class at first, until they are loaded). The Java Virtual machine immediately loads the sample class, storing the type information of the sample class in the method area.
2. The Java Virtual machine first allocates memory for a new sample instance in the heap area, and stores the memory address of the type information of the sample class in the memory of sample instance in a method area.
3. In the process of the JVM, each thread will have a method call stack, which is used to track a series of method calls in the running of the thread, each element in the stack is called the stack frame, and every time a thread calls a method, it presses a new frame into the method stack. The frames here are used to store the parameters of the method, the local variables, and the temporary data during the operation.

4. The Test1 before "=" is a variable defined in the main () method (a reference to a sample object), so it is added to the Java method call stack that executes the main thread of the main () method. and "=" will refer to the TEST1 variable to the sample instance in the heap area.
5. The JVM continues to create another instance of sample in the heap area and adds a Test2 variable to the method call stack of the Main method, which points to a new instance of sample just created in the heap area.

6. The JVM executes their printname () method sequentially. When the Java virtual machine executes the Test1.printname () method, the Java Virtual machine locates the sample instance in the heap area according to the reference held by the local variable test1, and then locates the type information of the sample class in the method according to the reference held by the sample instance. The byte code of the Printname () method is obtained, followed by the instructions contained in the Printname () method, and the execution begins.

Third, discrimination

The difference in the Java language Heap (heap) and stack (stack):
1. Stacks (stack) and heaps (heap) are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.
2. The advantage of the stack is that access is faster than the heap, second only to the registers directly located in the CPU. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. In addition, stack data can be shared (see below for details). The advantage of the heap is that the memory size can be dynamically allocated, and that the Java garbage collector automatically collects the data that is no longer in use without having to tell the compiler beforehand. The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.

2 types of data in Java:

One is the basic type (primitive types), a total of 8 classes, i.e. int, short, long, byte, float, double, Boolean, char (note that there is no basic type of string). This type of definition is passed through such as int a = 3; The form of long B = 255L is defined, called an automatic variable. An automatic variable is a literal value, not an instance of a class, which is not a reference to a class, where there is no class. such as int a = 3; Here's A is a reference to the int type, pointing to the literal value of 3. These literal data, due to the size of known, lifetime known (these literals are fixed in a program block, the program block exit, the field value disappears), for the pursuit of speed reasons, exist in the stack.
  

Stacks have a very important feature: the existence of data in the stack can be shared.  Suppose we define at the same time: int a = 3;  int b = 3; The compiler first handles int a = 3; First, it creates a reference to a variable in the stack, and then looks for an address with a literal value of 3, and if not, opens an address that holds the face value of 3 and then points a to 3. Then deal with int b = 3, after creating the reference variable for B, the B directly points to the address of 3 because it already has 3 of the literal value on the stack. In this way, there is a case where A and B both point to 3.

A reference to this literal is different from a reference to a class object. Assuming that references to two classes of objects also point to an object, if an object reference variable modifies the internal state of the object, then another object reference variable also instantly reflects the change. Conversely, modifying the value of a literal by reference does not result in another change in the value of the reference to that literal. As in the example above, we define the value of a and B and then make a=4; then, b is not equal to 4, or equal to 3. Inside the compiler, when A=4 is encountered, it will search the stack for a 4 literal value, and if not, reopen the address for a value of 4, and if so, point a directly to the address. Therefore the change of a value does not affect the value of B.
The other is wrapping class data, such as Integer, String, and double, which wraps the corresponding basic data types. All of these class data exist in the heap, and Java uses the new () statement to tell the compiler that it is dynamically created at run time, so it is more flexible, but the disadvantage is that it takes more time.

Iv. Summary

Java memory allocation is very clear, if you want to thoroughly understand, you can consult the JVM-related books. In Java, memory allocation is the most annoying string object, because of its particularity, so many programmers are easy to confuse, the next article in detail.

Related Article

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.