Java Memory allocation

Source: Internet
Author: User
Tags xms

With regard to the allocation of Java memory, many problems are vague and cannot be fully understood. Look at the information, want to dig deeper, thoroughly clear the Java memory allocation context, only because of the level of limited, did not achieve the desired effect, only in this article to the study to record, for the future study to provide reference, to avoid starting again.

One, Java memory allocation
1, Java has several storage areas?
* Register
--within the CPU, developers cannot control the allocation of registers through code, which is managed by the compiler
* Stack
--in Windows, the stack is the data structure to the low address extension, is a contiguous area of memory, that is, the top of the stack address and the maximum capacity of the stack is the system pre-defined.
-Advantages: Automatically assigned by the system, faster.
-Cons: Not flexible enough, but the programmer is out of control.
--Storage of basic data types, objects created during development (not during run)
* Heap
--is the data structure to the high address extension, is a discontinuous memory area
--There is no stack pointer in the heap, so there is no way to get support directly from the processor.
-the benefit of the heap is that there is great flexibility. As the Java compiler does not need to know how many storage areas to allocate from the heap, it is not necessary to know how long the stored data will survive in the heap.
* Static storage area and constant storage area
--static storage to hold variables of type static
--The constant store is used to hold values of the constant type (final) type, typically in read-only memory
* Non-RAM storage
--A Stream object that is to be sent to another machine.
--persisted objects, stored on disk
2. Java Memory allocation
--The underlying data type is allocated directly in the stack space;
--The formal parameter of the method, which is allocated directly in the stack space, when the method call is completed and recovered from the stack space;
--Reference data type, need to use new to create, both in the stack space allocation of an address space, but also in the heap space allocation of object class variables;
--The reference parameter of the method, allocates an address space in the stack space, and points to the object area of the heap space, when the method call is finished, it is reclaimed from the stack space;
--When the local variable new comes out, allocates space in the stack space and the heap space, when the local variable life cycle ends, the stack space is immediately reclaimed, and the heap space area waits for GC to recycle;
--the literal parameter, which is passed in the method invocation, is first allocated in the stack space and released from the stack space after the method call is completed.
--string constants are allocated in the DATA area, this is allocated in the heap space;
--arrays are allocated both in the stack space and the actual size of the array in the heap space!
3. Java Memory model
* The Java Virtual machine has roughly three logical parts of its governing memory: The method area, the Java stack, and the Java heap.
--the method area is statically allocated, and the compiler binds the variables to a storage location, and the bindings do not change at run time.
Constant pools, in which named constants, string constants, and static variables in the source code are saved in the method area.
Java stack is a logical concept, characterized by last-in-first-out. The space of a stack may be contiguous, or it may be discontinuous.
The most typical stack application is the invocation of a method, and the Java Virtual machine creates a method frame (frame) each time a method is called, and the corresponding method frame is ejected (pop) when the method exits. Is the data stored in the stack determined at run time?
Java heap allocation (heap allocation) means a memory management model that allocates and reclaims storage space at run time in a random order.
The data stored in the heap is often of a size, quantity, and lifetime that cannot be determined at compile time. The memory of the Java object is always allocated in the heap.
4. Java memory allocation Instance parsing
Chang (constant pool)Refers to some data that is determined at compile time and is saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, and also includes string constants.
The Chang 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, and if so, returns its reference, if not, Adds a string in the constant pool that is Unicode equals STR and returns its reference.
Cases:
String S1=new string ("Kvill");
String S2=s1.intern ();
System.out.println (S1==s1.intern ());//false
System.out.println (s1+ "" +s2);//Kvill Kvill
System.out.println (S2==s1.intern ());//true
There is no pre-eminent "Kvill" constant in this class, so there is no "kvill" in the constant pool at first, and when S1.intern () is called, a new "Kvill" constant is added to the constant pool, and the original "Kvill" in the constant pool still exists. 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.

String constant Pool problem
(1) string constant "+" number connection, the value of the string constant at compile time to determine down, take "a" + 1, compiler optimization in class is already A1.
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
(2) for a "+" connection that contains a string reference, it cannot be optimized by the compiler.
String a = "AB";
String BB = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = False
Because the referenced value cannot be determined during the program compilation period, that is, "a" + BB, which is allocated dynamically at run time and assigns the new address after the connection to B.
(3) for a final modified variable, it is parsed as a local copy of the constant value at compile time and 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.
String a = "AB";
Final String bb = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = True
(4) The JVM references a BB to a string, its value cannot be determined at compile time, and the return value of the method and "a" are dynamically concatenated and assigned the address B when the method is called after the program run time.
String a = "AB";
Final String bb = GETBB ();
String B = "a" + BB;
System.out.println ((A = = b)); result = False
private static string Getbb () {
return "B";
}
(5) The String variable is inefficient with the join operator (+).
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 ();
(6) Integer, double and other wrapper class and string have the same characteristics: invariant class.
The internal working mechanism of String str = "ABC" is very representative, taking a boolean example to illustrate the same problem.
The properties of the invariant class are generally defined as final and cannot be changed once the construction is complete.
The Boolean object has only a limited number of states: True and false, which defines the two Boolean objects as named constants:
public static Final Boolean true = new Boolean (true);
public static Final Boolean false = new Boolean (false);
These two named constants, like string constants, allocate space in a constant pool. Boolean.true is a reference, Boolean.false is a reference, and "ABC" is also a reference! Because Boolean.true is a class variable (static) that allocates memory statically, when you need many Boolean objects, you do not need to create individual instances with the new expression, and you can completely share the two static variables. The source code in its JDK is:
public static Boolean valueOf (Boolean b) {
return (b? True:false);
}
The basic data (Primitive) type of automatic boxing (autoboxing), unboxing (unboxing) is a new feature provided by JSE 5.0. Boolean B1 = 5>3; Equivalent to Boolean B1 = boolean.valueof (5>3); Better than Boolean B1 = new Boolean (5>3);
static void Foo () {
Boolean isTrue = 5>3; Basic type
Boolean B1 = boolean.true; objects created by static variables
Boolean b2 = boolean.valueof (isTrue);//Static Factory
Boolean B3 = 5>3;//Auto-boxing (autoboxing)
System.out.println ("B1 = = B2?" + (B1 = = b2));
System.out.println ("B1 = = B3?" + (B1 = = B3));
Boolean B4 = new Boolean (isTrue);////not suitable for use
System.out.println ("B1 = = b4?" + (B1 = = b4));//waste memory, have the time overhead of creating an instance
}//Here B1, B2, B3 point to the same Boolean object.
(7) If you ask: String x = "abc"; How many objects are created?
The exact answer is: 0 or 1. If "ABC" is present, the variable x holds the reference "ABC" without creating any objects.
If asked you: string str1 = new String ("abc"); How many objects have you created?
The exact answer is: 1 or 2. (at least 1 in the heap)
(8) for 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 looks for an address with a literal value of 3, finds an address that holds the literal value of 3, and then points A to the address of 3. then the int b = 3 is processed, and after the reference variable of B is created, B is pointed directly to the address of 3 because there are already 3 literals in the stack. In this case, A and B both point to 3.
5, heap, and non-heap (non-heap) memory
According to the official statement, "Java virtual machines have a heap, the heap is a runtime data region, and all class instances and arrays of memory are allocated from here." The heap is created when the Java Virtual machine is started. ”
You can see that the JVM primarily manages two types of memory: heap and non-heap.
Simply put, the heap is Java code memory, is left to developers to use;
Non-heap is the JVM left to itself, so the method area, the internal JVM processing or optimizing the required memory (such as the JIT compiled code cache), each class structure (such as running a constant pool, field and method data), and methods and construction methods of code are in non-heap memory.
Heap Memory allocation
The initial memory allocated by the JVM is specified by-XMS, which defaults to 1/64 of the physical memory;
The maximum allocated memory for the JVM is specified by-XMX, which defaults to 1/4 of the physical memory.
When the default free heap memory is less than 40%, the JVM increases the heap until the maximum limit of-xmx, and when the free heap memory is greater than 70%, the JVM reduces the heap until the minimum limit of-XMS.
So the server generally sets-xms,-xmx equal to avoid resizing the heap after each GC.
non-heap memory allocation
The JVM uses-xx:permsize to set the non-heap memory initial value, which defaults to 1/64 of the physical memory;
The maximum amount of non-heap memory is set by Xx:maxpermsize, which defaults to 1/4 of physical memory.
Example
-xms256m
-xmx1024m
-xx:permsize=128m
-xx:maxpermsize=256m

Java Memory allocation

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.