Deep Java core Java memory allocation principle explaining
Stack, heap, Chang, although the same is the Java memory allocation operation area, but its scope of application and function is very different. This article will delve into the Java core and explain in detail the knowledge of Java memory allocation.
Java memory allocation and management is one of the core technologies of Java, before we introduced Java memory management and memory leaks and Java garbage collection knowledge, today we go deep into the Java core, Learn more about the memory allocation in Java. In general, Java involves the following areas in memory allocation:
Register: We can't control it in the program
Stack: A reference to a primitive type of data and objects, but the object itself is not stored in the stack, but is stored in the heap
Heap: Storing data generated with new
Static domain: Static members that are stored in the object with static definitions
Constant pool: Storing constants
Non-RAM storage: Persistent storage space such as hard drives
Stacks in Java memory allocation
Some basic types of variable data and object reference variables that are defined in the function are allocated in the function's stack memory. When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the variable exits the scope, Java automatically frees the memory space allocated for the variable, and the memory space is immediately available for another use.
Heap in Java memory allocation
Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
After generating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program. A reference variable is equivalent to a name that is an array or an object.
A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The garbage collector takes off (releases) at a later indeterminate time. This is why the Java comparison accounts for memory.
In fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java! Chang (constant pool)
Chang refers to some data that is determined at compile time and is saved in the compiled. class file. In addition to the constant values (final) that contain the various basic types defined in the code (such as int, long, and so on) and object types (such as strings and arrays), there are also some symbolic references that appear as text, such as:
The fully qualified name of the class and interface;
The name and descriptor of the field;
Methods and names and descriptors.
The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used by that type, including direct constants (String,integer and floating point constants), and symbolic references to other types, fields, and methods.
For a string constant, its value is in a constant pool. The Chang in the JVM exists as a table in memory, and for string types there is a fixed-length constant_string_info table for storing literal string values, note that the table stores only literal string values and does not store symbol references. In this case, there should be a clearer understanding of where the string values in the constant pool should be stored. When the program executes, the constant pool is stored in the method area, not the heap.
Heap and Stack
The Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.
The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variable data (int, short, long, byte, float, double, Boolean, char) and object handle (reference).
Stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:
- int a = 3;
- int b = 3;
The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3.
At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B.
It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable.
String is a special wrapper class data. Can be used:
- String str = new string ("abc");
- String str = "ABC";
Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made. The second is to create an object reference to the string class in the stack str, and then through the symbol reference to the string constant pool to find there is no "ABC", if not, the "ABC" into the string constant pool, and the Str point to "ABC", if there is already "ABC" The STR directly points to "ABC".
Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.
- String str1 = "abc";
- String str2 = "abc";
- System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.
- String str1 =new string ("abc");
- String str2 =new string ("abc");
- System.out.println (STR1==STR2); False
The new method is to generate different objects. Each time one is generated.
So the second way to create multiple "abc" strings, in memory in fact there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program.
On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently. 1. The string is not the first of 8 basic data types, string is an object. Because the default value of the object is NULL, the default value of string is also null, but it is a special object that has some features that other objects do not have.
2. New string () and new String ("") are all declarations of a new empty string, that is, the empty string is not null;
3. String str= "Kvill"; string Str=new string ("Kvill") difference
Example:
- String s0= "Kvill";
- String s1= "Kvill";
- String s2= "kv" + "ill";
- System.out.println (S0==S1);
- System.out.println (S0==S2);
The result is: true True
First, we need to know the result. Java ensures that a string constant has only one copy.
Because the "Kvill" in S0 and S1 in the example are string constants, they are determined at compile time, so s0==s1 is true, and "kv" and "ill" are also string constants, and when a string is concatenated by multiple string constants, it is itself a string constant. So S2 is also parsed as a string constant at compile time, so S2 is also a reference to "Kvill" in the constant pool. So we come to s0==s1==s2; The string created with the new string () is not a constant and cannot be determined at compile time, so the string created by new string () is not placed in a constant pool and has its own address space.
Example:
- String s0= "Kvill";
- String s1=New string ("Kvill");
- String s2= "kv" + new string ("ill");
- System.out.println (S0==S1);
- System.out.println (S0==S2);
- System.out.println (S1==S2);
The result is: false false
In Example 2, S0 or "Kvill" in a constant pool, s1 because it cannot be determined at compile time, is a reference to the new object "Kvill" that was created at run time, S2 because there is a second part new String ("ill") so it cannot be determined at compile time, so it is also a newly created object " Kvill "The application of the", and understand that this will know why the result is obtained.
4. String.intern ():
One more point: the constant pool that exists in the. class file is loaded by the JVM at run time and can be expanded. The Intern () method of string is a method of extending a constant pool, and when a string instance str calls the Intern () method, Java looks for the same Unicode string constant in the constant pool, if any, returns its reference, if not, in the usual Add a string of Unicode equal to STR in the volume pool and return its reference; see the example.
Example:
- String s0= "Kvill";
- String s1=New string ("Kvill");
- String s2=New string ("Kvill");
- System.out.println (S0==S1);
- System.out.println ("**********");
- S1.intern ();
- S2=s2.intern (); Assign a reference to "Kvill" in the constant pool to S2
- System.out.println (S0==S1);
- System.out.println (S0==s1.intern ());
- System.out.println (S0==S2);
The result is: false false//although S1.intern () is executed, but its return value is not assigned to S1 TRUE//Description S1.intern () returns the reference true of "Kvill" in the constant pool
Finally I break a wrong understanding: Some people say, "using the String.intern () method, you can save a string class to a global string table, if a Unicode string with the same value is already in the table, Then the method returns the address of the existing string in the table, and if there are no strings of the same value in the table, register your own address in the table "If I interpret this global string table as Chang, his last word," if there are no strings of the same value in the table, register your own address in the table "Is wrong:
Example:
- String s1=New string ("Kvill");
- String S2=s1.intern ();
- System.out.println (S1==s1.intern ());
- System.out.println (s1+ "" +s2);
- System.out.println (S2==s1.intern ());
Result: false Kvill Kvill True
In this class we do not have the reputation of a "kvill" constant, so the constant pool in the beginning there is no "Kvill", when we call S1.intern () in the constant pool after the new "Kvill" constant, the original is not in the constant pool "Kvill" still exists, is not " Register your own address in the constant pool.
S1==s1.intern () is false to indicate that the original "Kvill" still exists; S2 is now the address of "Kvill" in the constant pool, so there is S2==s1.intern () true.
5. About Equals () and = =:
This is simple for string to compare whether the Unicode sequence of the two strings is equivalent, if equal returns true, and = = is the same as the address of the two strings, that is, a reference to the same string.
6. About the string is immutable
This said again a lot, as long as we know that the string instance once generated will not be changed, such as: string Str= "kv" + "ill" + "+" ans "; There are 4 string constants, first "KV" and "ill" generate "Kvill" in memory, and then "Kvill" and "Generate" Kvill "in memory, and finally generated" Kvill ans ", and the address of the string to the STR, This is because the "immutable" of string produces a lot of temporary variables, which is why it is recommended to use StringBuffer, because StringBuffer can be changed.
Here are some string-related FAQs:
Final usage and understanding in string final StringBuffer a = new StringBuffer ("111"); Final StringBuffer B = new StringBuffer ("222"); a=b;//This sentence compilation does not pass final stringbuffer a = new StringBuffer ("111"); A.append ("222");//Compile Through
As you can see, final is valid only for the reference "value" (that is, the memory address), which forces the reference to point only to the object that was initially pointed to, and changes its point to cause a compile-time error. Final is not responsible for the change in the object it points to.
Several examples of string constant pool problems
Here are a few common examples of comparative analysis and understanding:
- String a = "A1";
- String B = "a" + 1;
- System.out.println ((A = = b)); result = True
- String a = "atrue";
- String B = "a" + "true";
- System.out.println ((A = = b)); result = True
- String a = "a3.4";
- String B = "a" + 3.4;
- System.out.println ((A = = b)); result = True
Analysis: JVM for string constant "+" number connection, the program compile period, the JVM will be the constant string "+" connection optimization to the concatenated value, take "a" + 1, the compiler is optimized in class is already A1. The value of its string constants is determined at compile time, so the final result of the above program is true.
- String a = "AB";
- String BB = "B";
- String B = "a" + BB;
- System.out.println ((A = = b)); result = False
Analysis: JVM for string reference, because in the string "+" connection, there is a string reference exists, and the reference value in the program compilation period is not determined, that is, "a" + BB can not be optimized by the compiler, only during the program run time to dynamically allocate and the new address after the connection to B. So the result of the above program is also false.
- String a = "AB";
- Final String BB = "B";
- String B = "a" + BB;
- System.out.println ((A = = b)); result = True
Analysis: The only difference between [3] is that the BB string has a final decoration, and for a final modified variable, it is parsed at compile time to a local copy of the constant value stored in its own constant pool or embedded in its byte stream. So at this point the "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.
- String a = "AB";
- Final String BB = GETBB ();
- String B = "a" + BB;
- System.out.println ((A = = b)); result = False
- Private Static String GETBB () {
- return "B";
- }
Analysis: The JVM for the string reference BB, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to B, so the result of the above program is false.
From the above 4 examples can be obtained:
String s = "a" + "B" + "C"; is equivalent to string s = "abc"; String a = "a"; String B = "B"; String c = "C"; String s = a + B + C;
This is not the same, the end result equals:
- StringBuffer temp = new stringbuffer ();
- Temp.append (a). Append (b). append (c);
- String s = temp.tostring ();
From the above analysis results, it is not difficult to infer that the string using the Join operator (+) inefficiency reason analysis, such as the code:
- Public class Test {
- Public Static void Main (String args[]) {
- String s = null;
- for (int i = 0; i <; i++) {
- s + = "a";
- }
- }
- }
Every time you do it, you produce a StringBuilder object and then throw it away after append. The next time the loop arrives, it re-generates the StringBuilder object and then append the string so that it loops until the end. If we use the StringBuilder object directly for Append, we can save N-1 time to create and destroy objects. So for applications that want to concatenate strings in a loop, the StringBuffer or Stringbulider objects are generally used for append operations.
The Intern method of the string object is understood and analyzed:
- Public class Test4 {
- Private Static String a = "AB";
- Public Static void Main (string[] args) {
- String S1 = "a";
- String s2 = "B";
- String s = s1 + s2;
- System.out.println (s = = a);//false
- System.out.println (s.intern () = = a);//true
- }
- }
The problem with Java is that it is a constant pool. For the s1+s2 operation, a new object is recreated in the heap, and s holds the contents of the new object in the heap space, so s is not equal to the value of a. When you call the S.intern () method, you can return the address value of s in the constant pool, because the value of a is stored in a constant pool, so the values of s.intern and a are equal.
Summarize
A reference to the local variable data and objects (String, Array, object, and so on) that are used to hold some raw data types in the stack. But not the object content
The heap contains objects created using the New keyword.
A string is a special wrapper class whose reference is stored in the stack, and the object content must be set differently (Chang and heap) depending on how it was created. Some compile time has been created, stored in a string constant pool, and some runtime is created. Use the new keyword to store in the heap.
Deep Java core Java memory allocation principle explaining