Java Memory Consolidation-heap, Stack, Chang

Source: Internet
Author: User
Tags xms

Java Memory allocation:

1. Registers
We have no control over the program.

2. Stack
Stores the basic types of variable data, local variables, and references to objects, but the objects themselves are not stored in the stack, but are stored in the heap (new objects) or in a constant pool (string constant objects are stored in a constant pool. )

3. Heap
Holds an array of objects created with new.

To use the garbage collector, the heap is divided into three areas, called New Generation,old Generation or tenured Generation, and perm space. New generation is the space used to store the newly created object, which is used when the object is newly created. If they are used for a long time, they will be moved to the old Generation (or tenured Generation) by the garbage collector. Perm space is where the JVM stores meta data, such as classes, methods, string pools, and class-level details.

In the JVM, if 98% of the time is used for GC (garbage collection) and the available Heap size is less than 2%, the memory overflow exception is reported in Java Heap space

When the default free heap memory is less than 40%, the JVM increases the heap until the maximum limit. When the free heap is greater than 70%, the JVM reduces the heap-to-minimum limit. Therefore, on the server, the two are generally set to equal values to avoid resizing the heap after each GC.

Adjust the heap space method

-xms the initial heap size-xmx the maximum heap size. On most 32-bit machines, Sun's JVM, Java's heap space default size is 128MB.

The heap size is affected by three factors:

The data model of the related operating system is 32-bit or 64-bit 32-bit Windows: The heap size is generally limited to 1.5G to 2G/32 bit Linux: The heap size is generally limited to 2G to 3G 64-bit operating system unrestricted.

L system available Virtual memory limit

L The system can use physical memory to limit the initial-xms physical memory of 1/64 maximum-xmx physical memory 1/4

4. Static domain
Static members that are stored in the object with static definitions

5. Constant Pool
Holds string constants and basic type constants (public static final).

We primarily care about stacks, heaps, and constant pools

Stack:

The reference variables for some of the basic types of variables and objects defined in the function 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 in the stack, and when the scope of the variable is exceeded, Java automatically frees up the allocated memory space for that variable, which can be used immediately by another. Fast access, second only to registers.

The data size and life cycle in the stack can be determined, and when no reference points to the data, the data disappears

L data can be shared

The 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.

Heap

L need to dynamically allocate memory at runtime, so the access speed is slow

The garbage collector is responsible for the collection of objects in the heap, so the size and life cycle do not need to be determined and have great flexibility.

Constant pool

L Store string constants and basic type variables, such as String str1= "abc"; In fact "ABC" is in the constant pool inside.

When the program executes, the constant pool is stored in the method area, not the heap.

Data sharing in the stack

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.

For variables and constants of the underlying type: variables and references are stored in the stack, and constants are stored in the constant pool.

such as the following code:

int i1 = 9;

int i2 = 9;

int i3 = 9;

public static final int INT1 = 9;

public static final int INT2 = 9;

public static final int INT3 = 9;

for string

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.

For the code of string str = new String ("abc"), it is necessary to create new objects in the heap, regardless of whether their string values are equal or not, so that the burden of the program is compounded by the need to create new objects.

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 a previously created object, which is the sharing of data in a constant pool. 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.

String attribute

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= "Vill"; string Str=new string ("Kvill") difference

Example 1:

String s0= "Kvill";

String s1= "Kvill";

String s2= "kv" + "ill";

System.out.println (S0==S1); True

System.out.println (S0==S2); 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 Example 1 are string constants, they are determined at compile time, placed in a constant pool, so s0==s1 is true, and "kv" and "ill" are also string constants, when a string is concatenated with multiple string constants. It is certainly also 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. At this point we should know that there is only one string "Kvill" in the constant pool, so we get 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 the constant pool. They have their own address space.

Example 2:

String s0= "Kvill";

String S1=new string ("Kvill");

String s2= "kv" + new string ("ill");

System.out.println (S0==S1); False

System.out.println (S0==S2); False

System.out.println (S1==S2); False

In Example 2, S0 is also a reference to "Kvill" in a constant pool, s1 because it cannot be determined at compile time, so it is a reference to the new object "Kvill" created at run time, S2 because there is a second half part new String ("ill") so it cannot be determined at compile time, so it is also a newly created object " Kvill "Application, understand these also know why to arrive this result.

4. String.intern ():

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 a constant pool with the same Unicode string constant, if any, and returns its reference, if not, Adds a string in the constant pool that is Unicode equals STR and returns its reference; see the example.

Example:

String s0= "Kvill";

String S1=new string ("Kvill");

String S2=new string ("Kvill");

System.out.println (S0==S1); False one is a constant pool reference one is the object reference in the heap

System.out.println ("**********");

S1.intern (); Find a constant pool, if no kvill is created, at this time, because it exists, so do not create

S2=s2.intern (); Assign a reference to "Kvill" in the constant pool to S2

System.out.println (S0==S1); False Although S1.intern () is executed, but its return value is not assigned to S1 at this point S1 or in the heap

System.out.println (S0==s1.intern ()); True, S1.intern () returns a reference to "Kvill" in a constant pool

System.out.println (S0==S2); True S2 points to the constant pool at this point Kvill

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 ()); False S1 or point to the heap

System.out.println (s1+ "" +s2); Kvill Kvill

System.out.println (S2==s1.intern ()); 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 "Kvill" in the original heap 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. At compile time its string constant value is ok down, look for constant pool exists "A1", so the above program final result 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 used in the stack to hold some raw data types (String, array, object, and so on) but does not hold objects in the object content heap that are created with 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 depending on how it was created ( Chang and Heaps). Some compilation periods have been created, stored in a string constant pool, and some run-time is created. Using the new keyword, stored in the heap

(RPM) Java memory Consolidation-heap, Stack, Chang

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.