Java memory allocation mainly includes the following areas:
1. Register: We cannot control it in the program
2. Stack: stores basic types of data and object references, but The object itself is not stored in the stack, but is stored in the heap
3. Heap: stores the data generated by new
4. Static domain: stored in the object defined by static Member
5. Constant pool: store constants
6. Non-RAM (random access memory) storage: hard disk and other permanent storage space
******* *************************************************** ********
##Stack in Java memory allocation
Somebasic types defined in the function Variable data and object reference variables are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates memory space for the variable on the stack. When the variable exits the scope, Java will automatically release the memory space allocated for the variable, and the memory space can be used immediately. used for other purposes.
Heap in Java memory allocation
Heap memory is used to store objects created bynew and array. Memory allocated in the heap is managed by the Java virtual machine's automatic garbage collector.
After generating an array or object in the heap, you can also define a special variable in the stack, so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory. This variable becomes a reference variable of the array or object. A reference variable is equivalent to giving a name to an array or object. You can then use the reference variable in the stack to access the array or object in the heap in the program. A reference variable is equivalent to giving a name to an array or object. Reference variables are ordinary variables that are allocated on the stack when defined. The reference variables are released after the program runs outside its scope. The arrays and objects themselves are allocated in the heap. Even if the program runs outside the code block where the statement using new to generate the array or object is located, the memory occupied by the array and object itself will not be released. Arrays and objects have no reference variables pointing to them. , it becomes garbage and cannot be used anymore, but it still occupies the memory space and will be collected (released) by the garbage collector at an indeterminate time later. This is also the reason why Java takes up more memory.Actually, the variables in the stack point to the variables in the heap memory. This is the pointer in Java!
Constant pool(constant pool)
The constant pool refers to the pool that is determined during compilation and is saved in the compiled Some data in the .class file. In addition toconstant values (final)# including various basic types (such as int, long, etc.) and object types (such as String and arrays) defined in the code ## also contains some symbol references in text form, such as:
For String constants, their values are in the constant pool. The constant pool in the JVM exists in the form of a table in memory. For the String type, there is a fixed-length CONSTANT_String_info table used to store literal string values. Note: This table only stores literal string values, not symbols. Quote. Having said this, you should have a clear understanding of the storage location of string values in the constant pool.
When the program is executed, the constant pool will be stored in the Method Area instead of the heap.
Heap and Stack The Java heap is a runtime data area from which class (objects allocate space. These objects Created through instructions such as new, newarray, anewarray and multianewarray, they do not require program code to be explicitly released.
The heap is responsible for garbage collection.The advantage of the heap is that it can dynamically allocate memory. The size and lifetime do not need to be told to the compiler in advance, because it dynamically allocates memory at runtime, and Java's garbage collector will automatically collect these no longer used data. But the disadvantage is. , due to the need to dynamically allocate memory at runtime, the access speed is slower. The advantage of the stack is that the access speed is faster than the heap, second only to the register, and the stackdata can be shared. But the disadvantage is that the size and lifetime of the data stored in the stack must be determined , which lacks flexibility. The stack mainly stores some basic types of variable data (int, short, long, byte, float, double, boolean, char) and object handles (references). ************************************************ ************************ Here we mainly care about the stack, heap and constant pool. For stack It can be shared with objects in the constant pool, but cannot be shared with objects in the heap. The size and life cycle of the data in the stack can be determined. When there is no reference to the data, the data will disappear. The objects in the heap are recycled by the garbage collector, so the size and life cycle do not need to be determined, and there is great flexibility. String memory allocation: For strings, references to their objects are stored in the stack , If it has been created during compilation (directly defined with double quotes), it will be stored in the constant pool. If it is determined during runtime (new), it will be stored in the heap.. For equals equal strings, there is always only one copy in the constant pool and multiple copies in the heap. Such as the following code: Here is an explanation of the three yellow arrows, for generating a character through new string (assumed to be "china"), it will first check whether there is already a "china" object in the constant pool. If not, create a string object in the constant pool, and then create another object in the constant pool in the heap. The copy object of the "china" object. This is also an interview question: How many objects does Strings=newString(“xyz”); produce? One or two, if there is no "xyz" in the constant pool, it is two. The constant pool that exists in the .class file is loaded by the JVM during runtime and can be expanded. The intern() method of String is a method to expand the constant pool; when a String instance str calls the intern() method, Java checks whether there is a string constant with the same Unicode in the constant pool. If so, it returns its reference. If If not, add a Unicode string equal to str in the constant pool and return its reference The following code: Output result: false String constant pool A few examples of the problem: Analysis: [1] In [1], the JVM has a string reference due to the "+" connection in the string. , there is a string reference, and the value of the reference cannot be determined during program compilation, that is, "a" + bb cannot be optimized by the compiler. It can only be dynamically allocated during program running and assign the new address after connection to b. So the result of the above program is false. The only difference between [2] and [1] is that the bb string is final modified. For the final modified variable, it is parsed into a local copy of the constant value at compile time and stored in its own constant. Pooled or embedded into its bytecode stream. So the effect of "a" + bb and "a" + "b" at this time is the same. Therefore, the result of the above program is true. 【3】JVM cannot determine the value of string reference bb during compilation. Only after calling the method during program running, the return value of the method and "a" are dynamically connected and the address is allocated. b, so the result of the above program is false. Conclusion: String is a special packaging class, its reference is stored on the stack, and the object content must be determined according to the creation method (constant pool and Heap). Some are created during compilation and stored in the string constant pool, while others are created at runtime. Use the new keyword and store them in the heap. Allocation of variables and constants of basic types in memory For variables and constants of basic types, variables and references are stored On the stack, constants are stored in a constant pool. Such as the following code: 编译器先处理int i1 = 9;首先它会在栈中创建一个变量为i1的引用,然后查找栈中是否有9这个值,如果没找到,就将9存放进来,然后将i1指向9。接着处理int i2 = 9;在创建完i2的引用变量后,因为在栈中已经有9这个值,便将i2直接指向9。这样,就出现了i1与i2同时均指向9的情况。最后i3也指向这个9。 成员变量和局部变量在内存中的分配 对于成员变量和局部变量:成员变量就是方法外部,类的内部定义的变量;局部变量就是方法或语句块内部定义的变量。局部变量必须初始化。 形式参数是局部变量,局部变量的数据存在于栈内存中。栈内存中的局部变量随着方法的消失而消失。 成员变量存储在堆中的对象里面,由垃圾回收器负责回收。 如以下代码: 对于以上这段代码,date为局部变量,i,d,m,y都是形参为局部变量,day,month,year为成员变量。下面分析一下代码执行时候的变化: main方法开始执行:int date = 9; date局部变量,基础类型,引用和值都存在栈中。 Test test = new Test();test为对象引用,存在栈中,对象(new Test())存在堆中。 test.change(date); i为局部变量,引用和值存在栈中。当方法change执行完成后,i就会从栈中消失。 BirthDate d1= new BirthDate(7,7,1970); d1为对象引用,存在栈中,对象(new BirthDate())存在堆中,其中d,m,y为局部变量存储在栈中,且它们的类型为基础类型,因此它们的数据也存储在栈中。day,month,year为成员变量,它们存储在堆中(new BirthDate()里面)。当BirthDate构造方法执行完之后,d,m,y将从栈中消失。 main方法执行完之后,date变量,test,d1引用将从栈中消失,new Test(), new BirthDate()将等待垃圾回收。 String s1 = "china";
String s2 = "china";
String s3 = "china";
String ss1 = new String("china");
String ss2 = new String("china");
String ss3 = new String("china");
String s0= "kvill";
String s1=new String("kvill");
String s2=new String("kvill");
System.out.println( s0==s1 );
s1.intern();
s2=s2.intern(); //把常量池中"kvill"的引用赋给s2
System.out.println( s0==s1);
System.out.println( s0==s1.intern() );
System.out.println( s0==s2 );
false
true
true【1】
String a = "ab"= "b"= "a" +== b)); = "ab" String bb = "b"= "a" +== b)); = "ab" String bb == "a" +== b)); "b"
int i1 = 9; int i2 = 9; int i3 = 9; final int INT1 = 9; final int INT2 = 9; final int INT3 = 9;
class BirthDate { private int day; private int month; private int year; public BirthDate(int d, int m, int y) {
day = d;
month = m;
year = y;
} // 省略get,set方法………}public class Test { public static void main(String args[]) { int date = 9;
Test test = new Test();
test.change(date);
BirthDate d1 = new BirthDate(7, 7, 1970);
} public void change(int i) {
i = 1234;
}
}
The above is the detailed content of Analysis of heap, stack and constant pool of memory allocation in Java. For more information, please follow other related articles on the PHP Chinese website!