Post: Thinking and summary of Java memory

Source: Internet
Author: User
1. Java heap and stack
When the Java program is running, there are six places that can be used to save data:
(1) registers. The fastest storage area, located inside the processor, is very limited. It is allocated by the compiler as needed. We have no direct control over this.

(2) stack ). Resident in the regular RAM (Random Access Memory) area, which is a fast and especially effective data storage method, second only to registers. When creating a program, the Java compiler must accurately know the "length" and "time of existence" of all data stored in the stack ". This loses some flexibility, so the object handle is stored in the stack, but the Java object is not put in it.

(3) heap ). The Java object is saved. Different from stack, the most attractive thing is that the compiler does not have to know how much storage space should be allocated from the heap or how long the stored data will stay in the heap. Therefore, it is more flexible to store data in a heap. When creating an object, you only need to use the new command to compile the relevant code. When the code is executed, data is automatically saved in the heap. Of course, to achieve this flexibility, you must pay a certain price: It will take longer to allocate storage space in the heap!

(4) static storage. Here "static" refers to "in a fixed position" (although also in Ram ). During the running of the program, the static storage data will be waiting for calling at any time. The static keyword can be used to indicate that a specific element of an object is static. However, Java objects are never placed in static buckets.

(5) constant storage. Constant values are usually placed directly inside the program code. This is safe because they will never change. Some constants must be strictly protected, so you may consider placing them in read-only memory (ROM ).

(6) Non-ram storage. If the data is completely independent from a program, the program may still exist when it is not run and is out of the control scope of the program.

2. Stack and stack differences

Both stacks and stacks are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.

The Java heap is a runtime data zone and class (the object allocates space from it. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.

The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variables (, Int, short, long, byte, float, double, Boolean, char) and object handles.

A very important feature of stacks is that data in stacks can be shared. Suppose we define both:
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 the value 3 in the stack exists. If no value is found, store 3 and point A to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both A and B point to 3 at the same time.

At this time, if A is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of A does not affect the value of B.

Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.

String is a special packaging data. Available:
String STR = new string ("ABC ");
String STR = "ABC ";
The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object.
The second is to first create a string class object in the stack to reference the variable STR, and then find whether the stack contains "ABC". If not, store "ABC" into the stack and point STR to "ABC". If "ABC" already exists, direct STR to "ABC ".

Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.
String str1 = "ABC ";
String str2 = "ABC ";
System. Out. println (str1 = str2); // true
It can be seen that str1 and str2 point to the same object.

String str1 = new string ("ABC ");
String str2 = new string ("ABC ");
System. Out. println (str1 = str2); // false
The new method is used to generate different objects. Each time one is generated.

Therefore, the second method is used to create multiple "ABC" strings, and only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of string STR = new string ("ABC");, a new object is created in the heap, regardless of whether the string value is equal, whether it is necessary to create a new object, this increases the burden on the program.

On the other hand, NOTE: When we define classes using formats such as string STR = "ABC";, we always take it for granted that the STR object of the string class is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time.
Because of the immutable property of the string class, when the string variable needs to change its value frequently, you should consider using the stringbuffer class to improve program efficiency.

References:
Thoughts on java stack and stack
Http://www.duduwolf.com/post/3.asp

Chapter 1 everything is an object
Http://52cg.com/Training/KaiFa/java/200510/31900.html

3. About the size of memory space occupied by data in Java
-Test Environment
J2-midp1.0
-Test method:
Use the following statement to obtain the memory values before and after object creation. The difference value is the memory size occupied by the created object:
1. I = runtime. getruntime (). freememory ();
2. control = new control (control. head_move, 1, 1 );
3. j = runtime. getruntime (). freememory ();
4. system. Out. println (I-j );
This method is not accurate, because the JVM will run some things in the background from time to time. For example, running things in the background will occupy a certain amount of memory, if the background program runs between 1 and 3 sentences, it may cause inaccuracy.

To maintain correctness as much as possible, change the statement to the following: First GC, and then take the memory, so that the memory occupied by running in the background is released.
Runtime. getruntime (). GC ();
Thread. Yield ();
I = runtime. getruntime (). freememory ();
Test T = new test ();
Runtime. getruntime (). GC ();
Thread. Yield ();
J = runtime. getruntime (). freememory ();
System. Out. println (I-j );
However, this method may not guarantee that GC will be called. Therefore, the data obtained from each test is the same data obtained from multiple tests, and the data displayed after the heap size is stable, the pursuit of accuracy is as accurate as possible.

(1) I = runtime. getruntime (). freememory ();
Int T = 0;
Char A = 'a ';
Long L = 23410389;
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 0
[Conclusion] Because the basic data type is stored in the stack and does not occupy the heap memory, we can see that the value returned by freememory is the heap memory, so the value is 0.

(2)
I = runtime. getruntime (). freememory ();
String S2 = "1234567 ";
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 0
―――――――――――――――――――――――――――――――
I = runtime. getruntime (). freememory ();
String S2 = new string ("1234567 ");
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 56

[Conclusion] The string created using string S2 = "1234567" is stored in the stack, which does not occupy heap space, but uses string S2 = new string ("1234567 "); the created string is stored in the heap, which occupies 56 bytes of heap space.

(3)
Runtime. getruntime (). GC ();
Thread. Yield ();
I = runtime. getruntime (). freememory ();
Test T = new test (); // test is an empty class.
Runtime. getruntime (). GC ();
Thread. Yield ();
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 12

――――――――――――――――――――――――――――――――
Runtime. getruntime (). GC ();
Thread. Yield ();
I = runtime. getruntime (). freememory ();
Contorl c = new control (control. head_move, 1, 1 );
Runtime. getruntime (). GC ();
Thread. Yield ();
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 112

[Conclusion 1]: An empty object occupies 12 bytes of heap space and is considered as an object header.
[Conclusion 2]: A "head_move" object of a Zhanguo/control occupies the bytes heap space.

Why is it 112 bytes?
There are 25 non-static basic data types and reference variables in the control, while the memory occupied by INT, short, byte and other basic data types and reference variables is 4 bytes (see figure 4 ), therefore, the size is:
25*4 + 12 (object header) = 112

(4) In the above class test, add: Private int A = 0;
Result: 16 bytes,
From (3) we can know that empty objects occupy 12 bytes, so an int occupies 4 bytes of space.
Change int to another basic data type and perform the test using the same method. The following conclusions are obtained:
[Conclusion 1]: float, Boolean, byte, short, Int, and char occupy four bytes,
Long, double occupies 8 bytes of space (midp1.0 does not support float and double)
Reference variables, such as control C = NULL, occupying 4 bytes of space.

[Conclusion 2]: in Java, the type determines the behavior, not the size. Using BYTE can restrict data, but it cannot save memory, in the memory, bytes and INT occupy 4 bytes of space.

[Conclusion 3]: although a is a basic data type, it is a property of object T and is dynamically created at runtime. Therefore, it is also stored in the heap, occupies 4 bytes of heap space.

(5) Add the following statement to class test: and remove the int A variable added in (4.
Private Final Static Int J = 1;
Private Final Static int K = 4;
Private Static void testfunction (){
}
Result: 12
[Conclusion 1] The amount of heap space occupied by an object is only related to the non-static basic data types in the class and the referenced variables, but not to the static variables and functions. Static is stored in "static storage space" and does not occupy heap space.

[Conclusion 2] for classes that need to generate multiple objects, such as control, use static as much as possible for member variables in the class, because non-staitc variables in the object occupy a certain amount of space in the heap, when the number of objects is large, the occupied heap space will increase a lot. In this way, "application errors" may occur due to insufficient memory (mainly due to insufficient heap space.

(6)
I = runtime. getruntime (). freememory ();
Strin S = new string ("");
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 40
[Conclusion] An empty string occupies a 40-byte heap space, which is interpreted as the string header information. Avoid repeating the same string in the code, instead, we should use the method described in (2) above:
String S2 = "1234567" to generate a string.

(7)
Runtime. getruntime (). GC ();
Thread. Yield ();
I = runtime. getruntime (). freememory ();
Int A [] [] = new int [0] [0];
Runtime. getruntime (). GC ();
Thread. Yield ();
J = runtime. getruntime (). freememory ();
System. Out. println (I-j); // 16
----------------------------------------------------------------------------------
Int A [] [] = new int [1] [0]; // 36
Int A [] [] = new int [2] [0]; // 56
Int A [] [] = new int [3] [0]; // 76
Int A [] [] = new int [200] [0]; // 4016
Int A [] [] = new int [200] [1]; // 4816, because it is 200 more than the preceding int, It is 800 more

[Conclusion 1] each nested int [dim2] is an object. An int occupies 4 bytes of space, and each object has a 16-byte array object header.
[Conclusion 2] The memory consumption of the Two-dimensional array header is very high. For mobile phones with small memory, such as the Nokia old 40 series, it is best to change the two-dimensional array to a one-dimensional array.

References:
Discover how much memory an object consumes
Http://www.mywelt.net /? Q = node/577

Do you know the data size? -Do not spend too much time hiding class members.
Http://istudy.com.ru/Article/Software/Java/20051025/54,81897,0.html

Todo:
1. concerning the relationship between classes, variables, functions, and the jar size, consider the role of the obfuscator. What obfuscator can do does not have to be changed in the program.
2. The relationship between the agent program and the memory is further deepened, such as threads and GC.

???
1. After the Java program is compiled and programmed *. class files, are these files loaded into the memory at one time during runtime? If the program code is so long, it will consume a lot of memory to store the code? Where are they stored in the memory? The above mentioned areas are obviously not where the code is stored.


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.