"Java" Memory allocation comprehensive analysis of __java

Source: Internet
Author: User
Tags garbage collection wrapper

Reprint: https://blog.csdn.net/shimiso/article/details/8595564

This article will detail the Java memory allocation principle to help beginners learn Java more easily. There are a lot of such articles online, but most of them are fragmentary. From the perspective of cognitive process, this paper will bring readers a systematic introduction.

The first thing to know is that Java programs run on the JVM (Java Virtual Machine,java virtual machine), you can understand the JVM as a bridge between the Java program and the operating system, the JVM implements the Java platform independence, thus the importance of the JVM. So when learning the Java memory allocation principle, keep in mind that all of this is done in the JVM, and the JVM is the basis and prerequisite for the principle of memory allocation.

Simply speaking, a complete Java program runs with the following memory areas:

L Registers: The JVM internal virtual registers, the access speed is very fast, the program is not controllable.

L Stack: Save the values of local variables, including: 1. The value used to hold the base data type 2. Holds an instance of the class, that is, a reference (pointer) to the heap object. It can also be used to save frames when the method is loaded.

L Heap: Used to store dynamically generated data, such as new objects. Note that the created object contains only the individual member variables and does not include member methods. Because objects of the same class have their own member variables, stored in their own heap, but they share the methods of the class, not every time an object is created, the member method is copied once.

L constant Pool: The JVM maintains a constant pool for each loaded type, and a constant pool is an ordered set of constants used by this type. Includes direct constants (base type, String), and symbolic references to other types, methods, fields (1). Data in a pool is accessed through the index, as well as arrays. Because a constant pool contains all the symbolic references of a type to other types, methods, and fields, Chang plays a central role in the dynamic links in Java. A constant pool exists in the heap.

L Code snippet: used to store source code read from the hard disk.

L Data segment: Static member used to hold static definitions.

The following is a memory representation diagram:



The above figure describes the Java memory allocation, and then through an example to explain how the Java program is running in memory (note: The following picture quoted from the J2SE teacher of the school horse Soldier Courseware, the right is the program code, the left is the memory allocation diagram, I will add a note).

Preliminary knowledge:


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

2. Whether the ordinary type of variables or reference types of variables (commonly known as instances), can be as local variables, they can appear in the stack. Only the ordinary type of variable in the stack directly save its corresponding value, and the reference type of the variable to save a pointer to the heap area, through this pointer, you can find this instance in the heap area corresponding object. Therefore, the generic type variable occupies only one piece of memory in the stack, while the reference type variable occupies a chunk of memory in the stack area and the heap area.

Example:



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

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

3. Create two instances of the Birthdate class D1, D2, in the stack, respectively, hold the corresponding pointers to their respective objects. They call the constructor method with parameters when instantiated, so there are custom initial values in the object.



Invokes the Change1 method of the test object and takes date as an argument. When the JVM reads this code, it detects that I is a local variable, so I put I on the stack and assign the value of date to I.



Assign 1234 to I. It's a very simple step.



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


Invokes the Change2 method of the test object, with an instance D1 as a parameter. The JVM detects that the B parameter in the Change2 method is a local variable and immediately joins the stack, because it is a reference-type variable, so B saves the pointer in D1, where B and D1 point to objects in the same heap. Passing between B and D1 is a pointer.


A Birthdate object is also instantiated in the Change2 method and assigned to B. The internal execution process is that an object is new in the heap area, and the pointer to the object is saved in a B-space on the stack, when instance B no longer points to the object that the instance D1 points to, but the object that the instance D1 points to does not change, thus causing no effect on the D1.



The Change2 method completes, immediately releases the local reference variable B occupies the stack space, the attention only releases the stack space, the heap space waits for the automatic recycling.



Invokes the Change3 method of the test instance, with an instance D2 as a parameter. Similarly, the JVM allocates space for the local reference variable B in the stack, and the pointer in the D2 is placed in B, where D2 and B point to the same object. Calling the Setday method of instance B, in fact, is the Setday method that invokes the object that D2 points to.



The Setday method that invokes instance B affects D2 because they point to the same object.



The Change3 method completes and immediately releases the local reference variable B.


The above is the general situation of memory allocation in Java Program runtime. In fact, there is nothing to master the idea 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 basic type directly in the stack to save the value of the reference type to save only a pointer to the heap area, the real object in the heap. The base type is passed directly as a parameter, and the reference type passes the pointer.

Summary:


1. Distinguish what is an instance and what is an object. Class a= New Class (), at which point A is called an instance and cannot say that a is an object. Instance is in the stack, the object is in the heap, and the action instance is actually manipulating the object indirectly through the pointer of the instance. Multiple instances can point to the same object.

2. The data in the stack and the data destroyed in the heap are not synchronized. Once the method is finished, local variables in the stack are destroyed immediately, but the objects in the heap are not necessarily destroyed. Because other variables may also point to this object, it is destroyed only if the stack does not have a variable pointing to an object in the heap, and is not destroyed immediately, so it can be destroyed when the garbage collection is scanned.

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

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

The above analysis involves only stacks and heaps, and a very important area of memory: constant pools, where there are some inexplicable problems. Chang is what the top has been explained, and there is no need to understand how profound, just remember that it maintains a loaded class of constants on it. Next, combine some examples to illustrate the characteristics of a constant pool.

Preliminary knowledge:


Wrapper classes for basic types and basic types. The basic types are: Byte, short, char, int, long, Boolean. The basic types of wrapper classes are: Byte, short, Character, Integer, Long, Boolean. Note that case sensitivity is case-sensitive. The difference is: the basic types embodied in the program is a common variable, the basic type of packaging class is a class, reflected in the program is a reference variable. So the two storage locations in memory are different: the base type is stored in the stack, and the base type wrapper class is stored in the heap. These wrapper classes mentioned above implement the constant pool technique, and the other two types of floating-point numbers are not implemented in the wrapper class. In addition, the string type implements constant pool technology.

Example: [java]  view plain  copy public class test {       public  static void main (String[] args)  {                objpooltest ();       }           public static void objpooltest ()  {            int i = 40;            int i0 = 40;           integer  i1 = 40;           integer i2 =  40;           Integer i3 = 0;            integer i4 = new integer (; )            integer i5 = new integer (;  )          integer i6 = new integer (0);            Double d1=1.0;            Double d2=1.0;                       system.out.println ("i=i0\t"  +  (i == i0));           system.out.println ("I1=i2\t"

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.