Deep Java core Java memory allocation principle explaining

Source: Internet
Author: User

Java memory allocation and management is one of the core technologies of java, today we go deep into the Java core, in detail about the Java in memory allocation Knowledge. 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 the value of 3 in the stack, and if not found, 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 to 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

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 ();   The reference to "kvill" in the constant pool is assigned 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 a reference to "kvill" in a constant pool

True

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 ()); Results:

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 parsing: the JVM joins the "+" sign of a string constant, and the JVM optimizes the "+" connection of the constant string to the concatenated value, with "a" + 1, which is already A1 in class after the compiler has optimized it. 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 Parsing: JVM for string reference, because in the string "+" connection, there is a string reference exists, and the value of the reference in the program compilation period is not determined, that "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 is assigned 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 parsing: the only difference in [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"; }}} each time you make 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}} This is a constant pool problem in Java. 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

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.