Java Memory Allocation

Source: Internet
Author: User
Tags xms

Java memory management (I. Memory Allocation)
Keywords: memory allocation, constant pool
I. Java Memory Allocation
1,
How many storage regions does Java have?
* Registers
-- Within the CPU, developers cannot control register allocation through code, which is managed by the compiler.
* Stack
--
In Windows, the stack is a data structure extended to a low address and a continuous memory area. That is, the address at the top of the stack and the maximum size of the stack are pre-defined by the system.
--
Advantage: it is automatically allocated by the system, and the speed is fast.
-- Disadvantage: not flexible enough, but programmers cannot control it.
--
Stores basic data types and objects created during development (rather than running)
* Heap
-- Is the data structure extended to the high address, and is a non-sequential memory area
--
There is no stack pointer in the heap, so it cannot be directly supported from the processor.
--
The advantage of heap is its great flexibility. For example, the Java compiler does not need to know how many storage regions need to be allocated from the heap or how long the stored data will survive in the heap.
*
Static storage area and constant Storage Area
-- The static storage area is used to store static variables.
--
The constant storage area is used to store the value of the constant type (final) type, generally in read-only memory.
* Non-ram Storage
-- A stream object is sent to another machine.
 
-- Persistent objects are stored on disks.
2. Java Memory Allocation
-- The basic data type is directly allocated in the stack space;
--
The formal parameters of the method are directly allocated to the stack space. After the method is called, The stack space is reclaimed;
--
To reference the data type, you must use new to create a class variable that allocates an address space in the stack space and objects in the heap space;
--
Method reference parameters: Allocate an address space in the stack space and point to the object area of the heap space. After the method is called, it is reclaimed from the stack space;
-- Local variable new
When it comes out, the stack space and heap space are allocated. When the lifecycle of a local variable ends, the stack space is immediately reclaimed, And the heap space is waiting for GC to be recycled;
-- Literal passed in when the method is called
Parameter, which is first allocated in the stack space, and then released from the stack space after the method call is complete;
-- String constants are allocated in the data area. This is allocated in the heap space;
--
The array not only allocates the array name in the stack space, but also allocates the actual size of the array in the heap space!
3. Java Memory Model
*
Java Virtual Machine divides its memory into three logical parts: Method Area, java stack, and java stack.
--
The method area is statically allocated. The Compiler binds variables to a storage location and these bindings do not change at runtime.
Constant pool, named constants in source code, string constants, and static
The variables are stored in the method area.
-- Java stack is a logical concept that features a forward, forward, and backward. The space of a stack may be continuous or discontinuous.
 
The most typical stack application is a method call. Each time a Java Virtual Machine calls a method, a method frame is created.
Method Frame pop ). Is the data stored in the stack determined at runtime?
-- Java heap allocation
Allocation) indicates the memory management model for Bucket allocation and recovery at runtime in random order.
 
The size, quantity, and life cycle of the data stored in the heap are often uncertain during compilation. The memory of Java objects is always allocated in heap.
4. Analysis of Java memory allocation instances
 
Constant pool (constant
Pool) refers to some data that is determined during the compilation period and stored in the compiled. Class file. It includes constants in classes, methods, interfaces, and other fields, as well as string constants.
 
The constant pool is loaded by JVM at 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 the constant pool has the same UNICODE String constant, if yes, its reference is returned. If no, a string with Unicode equal to STR is added to the constant pool and Its Reference is returned.
 
Example:
String S1 = new string ("kvill ");
String S2 = s1.intern ();
 
System. Out. println (S1 = s1.intern (); // false
System. Out. println (S1 + "" + S2
); // Kvill
System. Out. println (s2 = s1.intern (); // true
 
This class does not have a "kvill" constant in advance, so there is no "kvill" in the constant pool at the beginning. When s1.intern () is called () then, a new "kvill" constant is added to the constant pool. The original "kvill" that is not in the constant Pool still exists. If S1 = s1.intern () is false, the original "kvill" still exists. S2 is now the address of "kvill" in the constant pool, so S2 = s1.intern () is true.

 

String
Constant pool problems
(1) For the "+" join of the string constant, the value of the String constant is determined during the compilation period. Take "A" + 1 as an example, after the compiler is optimized, it is already A1 in the class.
 
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) "+" Connections containing string references cannot be optimized by the compiler.
String A = "AB ";
String BB =
"B ";
String B = "A" + BB;
System. Out. println (A = B); // result
= False
The referenced value cannot be determined during the program compilation period, that is, "a" + BB. The new address after the connection is assigned to B only dynamically during the runtime.
(3)
For final modified variables, it is parsed as a local copy of a constant value during compilation and stored in its own constant pool or embedded in its byte code stream. Therefore, "a" + BB and "A" +
"B" has the same effect.
String A = "AB ";
Final string BB = "B ";
String B
= "A" + BB;
System. Out. println (A = B); // result = true
(4)
The JVM cannot determine the value of a string referenced by BB during the compilation period. After calling a method during the runtime, it dynamically connects the return value of the method to "A" and assigns the address B.
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 efficiency of using the concatenation operator (+) for string variables is low.
 
String S = "A" + "B" + "C"; it is equivalent to string S = "ABC ";
String A = "";
 
String B = "B ";
String c = "C ";
String S = A + B + C;
 
This is different. The final result is equal:
Stringbuffer temp = new stringbuffer ();
 
Temp. append (a). append (B). append (C );
String S = temp. tostring ();
(6)
Integer, double, and other packaging classes have the same characteristics as string: Unchanged class.
String STR =
The internal working mechanism of "ABC" is representative. Taking boolean as an example, we will illustrate the same problem.
The attributes of the unchanged class are generally defined as final. Once constructed, they cannot be changed.

Boolean objects have only two limited states: true and false. These two Boolean objects are defined as named constants:
Public static
Final Boolean true = new Boolean (true );
Public static final Boolean false
= New Boolean (false );
The two named constants are the same as the string constants and allocate space in the 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 will be statically allocated to the memory, when many Boolean objects are required, you do not need to use the new expression to create each instance. You can completely share these two static variables. In its JDK, the source code is:

Public static Boolean valueof (Boolean B ){
Return (B? True:
False );
}
The autoboxing and unboxing types of basic data (primitive) are
5.0 new features. 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; // The object created by the static variable
 
Boolean b2 = Boolean. valueof (istrue); // static Factory
Boolean B3 =
5> 3; // autoboxing)
System. Out. println ("b1 = b2? "+ (B1 = b2 ));

System. Out. println ("b1 = B3? "+ (B1 = B3 ));
Boolean B4 = new
Boolean (istrue); // not applicable
System. Out. println ("b1 = B4? "+ (B1 =
B4); // memory waste and time overhead for instance Creation
} // Here b1, b2, and B3 point to the same Boolean object.
(7) If you ask: String x
= "ABC"; how many objects are created?
The correct answer is: 0 or 1. If "ABC" exists, variable X holds the reference "ABC" without creating any objects.
 
If you ask: String str1 = new string ("ABC"); how many objects have been created?
 
The exact answer is: 1 or 2. (At least one in heap)
(8) For int A = 3; int B = 3;
The compiler first processes int A =
3; first, it creates a reference with the variable A in the stack, and then finds whether there is an address with the nominal value of 3. If it is not found, it opens an address for storing the nominal value of 3, then point A to the address 3. Then process int B =
3. After the referenced variable of B is created, B is directed to the address of 3 because there is already 3 in the stack. In this way, both A and B point to 3 at the same time.
5. Heap and non-heap memory
 
According to the official statement: "A Java virtual machine has a heap. The heap is the runtime data area, and the memory of all class instances and arrays is allocated from this place. The heap is created when the Java Virtual Machine is started ."
 
JVM manages two types of memory: heap and non-heap.
In short, heap is the memory available for Java code and is reserved for developers;
 
Non-heap is reserved for the JVM, so the memory required for processing or optimization in the Method Area and JVM (such as the code cache after JIT compilation) and the code for each class structure (such as the runtime data pool, field, and method data) and method and constructor are all in non-heap memory.

Heap Memory Allocation
The memory initially allocated by JVM is specified by-XMS. By default, it is 1/64 of the physical memory;
 
The maximum memory allocated by the JVM is specified by-xmx. By default, it is 1/4 of the physical memory.
 
By default, when the free heap memory is less than 40%, the JVM will increase the heap until the maximum limit of-xmx. When the free heap memory is greater than 70%, the JVM will reduce the minimum limit of heap until-XMS.
 
Therefore, the server generally sets-XMS and-xmx to be equal to each other to avoid adjusting the heap size after each GC.
Non-heap memory allocation
 
JVM uses-XX: permsize to set the non-heap memory initial value. The default value is 1/64 of the physical memory;
 
Set the maximum non-heap memory size by XX: maxpermsize. The default value is 1/4 of the physical memory.
Example
-Xms256m
 
-Xmx1024m
-XX: permsize = 128 m
-XX: maxpermsize = 256 m

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.