JAVA memory management summary, java Memory Management Summary
1. How does java manage memory?
Java memory management is the issue of object allocation and release. (Two parts)
Allocation: the memory is allocated by the program. The programmer needs to apply for memory space for each object through the keyword new (except for the basic type). All objects are in the Heap).
Release: objects are determined and executed by the garbage collection mechanism, which simplifies the work of programmers. But at the same time, it also increases the JVM's work. To release objects correctly, GC must monitor the running status of each object, including application, reference, reference, and assignment of objects. GC must monitor all objects.
2. What is java Memory leakage?
In Java, memory leakage is the existence of some allocated objects. These objects have the following two features: first, these objects are reachable, that is, in Directed Graphs, A path can be connected to it (that is, a reference to the memory object still exists). Second, these objects are useless, that is, they will not be used by the program in the future. If the objects meet these two conditions, these objects can be identified as memory leaks in Java. These objects are not recycled by GC, but occupy the memory.
3. JVM memory area composition
Java divides memory into two types: stack memory and heap memory 1. The basic type variables defined in the function and the referenced variables of the object are allocated in the function stack memory; 2. Heap memory is used to store the objects and arrays created by new and instance variables of objects. When a variable is defined in a function (code block), java allocates memory space for the variable in the stack, when the scope of the variable is exceeded, java Automatically releases the memory space allocated for the variable. The memory allocated in the heap is managed by the java Virtual Machine's automatic garbage collector.
Advantages and disadvantages of heap and stack
The advantage of heap is that the memory size can be dynamically allocated, and the lifetime does not need to be told to the compiler in advance because it dynamically allocates memory at runtime.
The disadvantage is that the memory needs to be dynamically allocated at runtime, And the access speed is slow. The advantage of the stack is that the access speed is faster than the heap speed, second only to the registers directly located in the CPU.
In addition, 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.
4. How is data stored in memory in Java?
A) Basic Data Types
Java has eight basic data types: int, short, long, byte, float, double, boolean, and char (note that there is no basic type of string ). This type is defined in the form of int a = 3; long B = 255L. For example, int a = 3; here, a is a reference pointing to the int type, pointing to the literal value of 3. Because of the size and lifetime of the nominal value data, we can see that (the nominal value is defined in a program block, and the field value disappears after the program block exits). For the reason of speed, it exists in the stack.
In addition, the stack has a very important feature, that is, data in the stack can be shared. For example, we also define:
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 3, not found, open up an address that stores the nominal value of 3, and then point a to the address of 3. Then process int B = 3. After the referenced variable "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. After defining the values of a and B, make a = 4; then, B will not be equal to 4 or 3. In the compiler, when encountered, it will re-search whether there are 4 literal values in the stack, if not, re-open the address to store 4 values; if there is already, direct a to this address. Therefore, changing the value of a does not affect the value of B.
B) object
In Java, creating an object involves two steps: Object declaration and instantiation. The following uses an example to describe the object's memory model. Assume that a Rectangle class is defined as follows:
Public class Rectangle {
Double width;
Double height;
Public Rectangle (double w, double h ){
W = width;
H = height;
}
}
(1) Memory Model for object Declaration
Use Rectangle rect. When declaring an object rect, the stack memory allocates memory space for the reference variable rect of the object, but the Rectangle value is null, indicating that rect is an empty object. Null objects cannot be used because they have not referenced any "entity ".
(2) Memory Model for Object Instantiation
When rect = new Rectangle (); is executed, two tasks are performed: allocate memory for the class member variable width and height in the heap memory, initialize it to the default values of each data type, and then perform Explicit initialization (the initialization value when the class is defined). Finally, call the constructor to assign values to the member variables. Return the reference (equivalent to the first address) of the object in heap memory to the reference variable rect. Then, you can reference the object in heap memory through rect.
C) create multiple object instances
A class can create multiple different object instances by using the new operator. These object instances will be allocated different memory spaces in the heap, changing the status of one of the objects does not affect the status of other objects. For example:
Rectangle r1 = new Rectangle (3, 5 );
Rectangle r2 = new Rectangle (4, 6 );
In this case, the heap memory allocates memory space for the member variables width and height of the two objects respectively. The space occupied by the two objects in the heap memory is different from each other. If:
Rectangle r1 = new Rectangle (3, 5 );
Rectangle r2 = r1;
Only one object instance is created in the heap memory, and two object references are created in the stack memory. Both object references point to one object instance at the same time.
D) Packaging
The basic types all have corresponding packaging classes: for example, int corresponds to Integer classes and double corresponds to Double classes. The basic types are defined directly in the stack. If you use a packaging class to create objects, just like a common object. For example, int I = 0; I is directly stored in the stack. Integer I (I is an object at this time) = new Integer (5); in this way, I object data is stored in the heap, And I references are stored in the stack, operate on objects through stack references.
E) String
String is a special packaging data. You can use either of the following methods: String str = new String ("abc"); String str = "abc ";
The first method is the same as the creation process of a common object;
In the second method, Java converts the statement into the following steps:
(1) first define a reference variable for the String class object named str: String str;
(2) check whether there is an address with the "abc" value in the stack. If there is no address, open a storage address with the "abc" value"
Create a new String class Object o, point the o String value to this address, and
Write down the referenced object o next to this address. If an address with a value of "abc" already exists, search for the object o and
Return to the o address.
(3) Point str to the address of object o.
It is worth noting that the String values in the String class are stored directly. But such as String str = "abc ";
The string value stores a reference pointing to data in the stack.
To better illustrate this problem, we can use the following code for verification.
String str1 = "abc ";
String str2 = "abc ";
System. out. println (s1 = s2); // true
Note that str1.equals (str2); is not used here, because it will compare the values of the two strings to see if they are equal. =. According to JDK instructions, the true value is returned only when both references point to the same object. What we need to see here is whether both str1 and str2 point to the same object.
Let's look at the following code.
String str1 = new String ("abc ");
String str2 = "abc ";
System. out. println (str1 = str2); // false
Two references are created. Two objects are created. The two references point to two different objects. The above two sections of Code describe that as long as new () is used to create an object, it will be created in the heap, and its string is stored separately, even if it is the same as the data in the stack, it will not share data with the stack.
F) array
When defining an array, int x []; or int [] x;, create an array reference in the stack memory and use this reference (that is, the array name) to reference the array. X = new int [3]; allocate three int-type data storage spaces in the heap memory, and place the first address of the heap memory in the stack memory, each array element is initialized to 0.
G) static variables
Variables and Methods Modified with static are actually "fixed location"-static storage of these variables and methods in the memory, which can be understood as the total memory space of all instance objects. Static variables are similar to global variables in C. static variables indicate Memory sharing, that is, each of its instances points to the same memory address. When static is used, it indicates that the JVM is static, and its reference (including indirect reference) points to the same location. In that location, you changed it, it will not become the original. If you clear it, it will not come back. When Will static variables and methods be initialized? For two different class attributes, static attributes and instance attributes, the initialization time is different. The instance attribute is initialized when an instance is created. The static attribute is initialized when the class is loaded, that is, the class is used for the first time. The subsequent instance creation is not initialized again. We often see examples similar to the following to illustrate this problem:
Class Student {
Static int numberOfStudents = 0;
Student ()
{
NumberOfStudents ++;
}
}
Every time a new Student instance is created, numberOfStudents is constantly increasing, and all Student instances access the same numberOfStudents variable, in fact, the int numberOfStudents variable is only stored in one location in the memory.
5. Java memory management instance
Multiple Parts of the Java program (methods, variables, and objects) reside in the following two locations in the memory: heap and stack. Now we only care about three types of things: instance variables, local variables and objects:
Instance variables and objects reside on the stack.
Local variables reside on the stack
Let's look at a java program and see how each part is created and mapped to the stack and heap:
Public class Dog {
Collar c;
String name;
// 1. The main () method is located on the stack.
Public static void main (String [] args ){
// 2. Create a reference variable d on the stack, but the Dog object does not exist
Dog d;
// 3. Create a new Dog object and assign it to d reference variable
D = new Dog ();
// 4. Pass a copy of the referenced variable to the go () method
D. go (d );
}
// 5. Place the go () method on the stack and use the dog parameter as a local variable.
Void go (Dog dog ){
// 6. Create a new Collar object on the heap and assign it to the Dog instance variable
C = new Collar ();
}
// 7. Add setName () to the stack and use the dogName parameter as its local variable.
Void setName (String dogName ){
// The instance object of 8. name also references the String object
Name = dogName;
}
// 9. After the program is executed, setName () will be completed and cleared from the stack. At this time, the local variable dogName will also disappear, even though the String it references is still on the stack.
}
6. Garbage collection mechanism:
(Question 1: What is the garbage collection mechanism ?) Garbage collection is a kind of dynamic storage management technology that automatically releases objects that are no longer referenced by programs, and implements automatic Resource Recovery based on specific garbage collection algorithms. When an object is no longer referenced, the memory recycles the occupied space so that the space is used by new objects to avoid Memory leakage. (Question 2: What are the characteristics of java garbage collection ?) The JAVA language does not allow programmers to directly control the use of memory space. JRE is responsible for automatic memory space allocation and recovery in the background, especially the garbage collection (garbagecollection, also called garbage collection ), only one super thread provided by the runtime environment can be used for monitoring and control. (Question 3: When will the Garbage Collector run ?) Generally, garbage collection is automatically performed when the CPU is idle or the space is insufficient, while programmers cannot precisely control the timing and sequence of garbage collection. (Question 4: What objects meet the garbage collection conditions ?) When no get thread can access an object, the object meets the garbage collection condition. (Question 5: How does the Garbage Collector work ?) If the garbage collector finds that an object cannot be accessed by any live thread, it considers that the object meets the deletion criteria and adds it to the recycle queue, but does not destroy the object immediately, it is unpredictable when memory is destroyed and released. Garbage collection cannot be executed forcibly. However, Java provides some methods (such as: System. gc () method), allows you to request JVM to execute garbage collection, instead of requiring the virtual opportunity to satisfy the request as much as possible, but cannot ensure that JVM deletes all unnecessary objects from the memory. (Question 6: Can a java program use up memory ?) Yes. The garbage collection system tries to delete objects from memory when they are not used. However, if you keep too many live objects, the system may exhaust the memory. The garbage collector cannot ensure that there is sufficient memory. It can only ensure that the available memory is managed as efficiently as possible. (Question 7: how to display the object to meet the garbage collection condition ?) (1) Empty reference: when the object does not reach the reference, it will meet the condition of garbage collection. That is to say, if there is no reference to the object, the object can be deleted, so we can set the reference variable to null to meet the garbage collection condition.
StringBuffer sb = new StringBuffer ("hello ");
System. out. println (sb );
Sb = null;
(2) assign a value to the referenced variable again: You can set the referenced variable to reference another object to cancel the reference relationship between the referenced variable and an object.
StringBuffer sb1 = new StringBuffer ("hello ");
StringBuffer sb2 = new StringBuffer ("goodbye ");
System. out. println (sb1 );
Sb1 = sb2; // at this time, "hello" meets the recycling conditions
(3) Objects Created in the method: The created local variables only exist during the validity period of the method. Once this method is returned, the object created in this method meets the garbage collection condition. An obvious exception is that the method returns an object.
Public static void main (String [] args ){
Date d = getDate ();
System. out. println ("d =" + d );
}
Private static Date getDate (){
Date d2 = new Date ();
StringBuffer now = new StringBuffer (d2.toString ());
System. out. println (now );
Return d2;
}
(4) isolated reference: In this case, the recycled object still has reference, which is called isolated island. If the two instances exist, they reference each other and all other references of the two objects are deleted, and any other thread cannot access any of these two objects. It can also meet the garbage collection conditions.
Public class Island {
Island I;
Public static void main (String [] args ){
Island i2 = new Island ();
Island i3 = new Island ();
Island i4 = new Island ();
I2. I = i3;
I3. I = i4;
I4. I = i2;
I2 = null;
I3 = null;
I4 = null;
}
}
(Question 8: Cleanup before garbage collection ------ finalize () method) java provides a mechanism that enables you to run some code before the object is to be reclaimed. This code is located in the finalize () method. All classes inherit this method from the Object class. The garbage collector cannot delete an object. Therefore, the Code stored in finalize () cannot be guaranteed to run. Therefore, we recommend that you do not override finalize ();
7. final problems:
Final makes the modified variable "unchanged", but because the object type variable is essentially "Reference", it also has two meanings: The reference itself remains unchanged ?, And the referenced object .? The reference itself remains unchanged:
Final StringBuffer a = new StringBuffer ("immutable ");
Final StringBuffer B = new StringBuffer ("not immutable ");
A = B; // compilation Error
Final StringBuffer a = new StringBuffer ("immutable ");
Final StringBuffer B = new StringBuffer ("not immutable ");
A = B; // compilation Error
The referenced object remains unchanged:
Final StringBuffer a = new StringBuffer ("immutable ");
A. append ("broken! "); // Compiled
Final StringBuffer a = new StringBuffer ("immutable ");
A. append ("broken! "); // Compiled
It can be seen that final is only valid for the referenced "value" (that is, the memory address of the object it points to), and forces the reference to point only to the object initially pointed, changing the point will cause compilation errors. Final is not responsible for the changes to the objects it points. This is very similar to the = Operator: = Operator is only responsible for referencing the "value" equal, as to whether the content of the object pointed to by this address is equal, the = operator does not matter. For example:
Public class Name {
Private String firstname;
Private String lastname;
Public String getFirstname (){
Return firstname;
}
Public void setFirstname (String firstname ){
This. firstname = firstname;
}
Public String getLastname (){
Return lastname;
}
Public void setLastname (String lastname ){
This. lastname = lastname;
}
}
Public class Name {
Private String firstname;
Private String lastname;
Public String getFirstname (){
Return firstname;
}
Public void setFirstname (String firstname ){
This. firstname = firstname;
}
Public String getLastname (){
Return lastname;
}
Public void setLastname (String lastname ){
This. lastname = lastname;
}
}
Compile the Test method:
Public static void main (String [] args ){
Final Name name = new Name ();
Name. setFirstname ("JIM ");
Name. setLastname ("Green ");
System. out. println (name. getFirstname () + "" + name. getLastname ());
}
Public static void main (String [] args ){
Final Name name = new Name ();
Name. setFirstname ("JIM ");
Name. setLastname ("Green ");
System. out. println (name. getFirstname () + "" + name. getLastname ());
}
Understanding final issues has important meanings. Many program vulnerabilities are based on this ---- final can only ensure that the reference always points to a fixed object, but cannot ensure that the state of that object remains unchanged. In multi-threaded operations, an object will be shared or modified by multiple threads. Unintentional modifications made by one thread to the object may cause another thread to crash. The solution to an error is to declare the object as final when it is created, so that it "remains unchanged ". In fact, it is futile. There is also a noteworthy part in Final: first look at the following sample program:
Class Something {
Final int I;
Public void doSomething (){
System. out. println ("I =" + I );
}
}
Class Something {
Final int I;
Public void doSomething (){
System. out. println ("I =" + I );
}
}
For class variables, the Java Virtual Machine will automatically initialize. If an initial value is given, the initialization is the initial value. If not, initialize it as the default initial value of the type variable. However, for class variables modified with final, the virtual machine does not assign the initial value to them. It must be assigned a clear value before the constructor ends. It can be changed to "final int I = 0 ;".
8. How to write programs more robust:
1. Release reference of useless objects as soon as possible. A good way is to enable the reference variable to be automatically set to null after exiting the active domain when using a temporary variable, suggesting that the Garbage Collector collects the object to prevent memory leakage. For instances with pointers, jvm will not recycle this resource, because garbage collection will take null objects as garbage, improving the efficiency of GC collection mechanism;
2. Use String str = "hello"; to define a String. Do not use String str = new String ("hello. Because you need to use strings with the same content, you do not have to create a new String each time. For example, we need to initialize a String reference variable named s in the constructor and set it as the initial value. We should do this:
Public class Demo {
Private String s;
Public Demo (){
S = "Initial Value ";
}
}
Public class Demo {
Private String s;
...
Public Demo {
S = "Initial Value ";
}
...
}
Rather
S = new String ("Initial Value ");
S = new String ("Initial Value ");
The latter calls the constructor every time to generate a new object, which has low performance and high memory overhead and has no significance. Because the String object cannot be changed, for strings with the same content, it can be expressed as long as a String object. That is to say, the constructor above is called multiple times to create multiple objects, and their String type attribute s points to the same object.
3. A large number of String processing is inevitable in our program. To avoid using strings, we should use StringBuffer in large quantities because String is designed as immutable class, so all its objects are immutable objects. Please refer to the following code;
String s = "Hello ";
S = s + "world! ";
String s = "Hello ";
S = s + "world! ";
In this Code, s originally points to a String object with the content "Hello". Then we perform the + operation on s. Does the object s points to change? The answer is no. At this time, s points to another String object instead of the original object, and the content is "Hello world! ", The original object still exists in the memory, but the reference variable s no longer points to it. Through the above description, we can easily draw another conclusion, if you often make various modifications to the string, or make unforeseen modifications, therefore, using String to represent strings will cause a large memory overhead. Because the String object cannot be changed after it is created, a String object is required for each different String. In this case, you should consider using the StringBuffer class, which allows modification, instead of generating a new object for each different string. In addition, the conversion between the two types of objects is very easy.
4. Use as few static variables as possible, because static variables are global and GC will not be recycled;
5. Avoid creating and initializing a large number of objects in the class constructor as much as possible, and avoid unnecessary memory resource waste when calling the constructor of its own class, especially for large objects, JVM suddenly requires a large amount of memory, which will inevitably trigger GC to optimize the system memory environment. The declared array space is displayed, and the number of applications is large. The following are the time required to initialize different types of objects:
|
Operation |
Example |
Standardization time |
|
Local assignment |
I = n |
1.0 |
|
Instance assignment |
This. I = n |
1.2 |
|
Method call |
Funct () |
5.9 |
|
New Object |
New Object () |
980 |
|
Create an array |
New int [10] |
3100 |
From table 1, we can see that it takes 980 units of time to create an object, which is 980 times of the local value assignment time and 166 times of the method call time, it takes more time to create an array.
6. Try to use the object pool technology in appropriate scenarios to improve system performance and reduce overhead. However, note that the size of the Object pool should not be too large and the invalid objects should be cleared in time to release memory resources, consider the memory resource limits of the application runtime environment to avoid overestimating the number of memory resources provided by the runtime environment.
7. When a large collection object has a large data volume of business objects, you can consider processing them in multiple parts and then solve the policy of releasing one piece.
8. Do not create objects in frequently called methods, especially avoid creating objects in loops. You can use hashtable as appropriate. The vector creates a group of object containers and then retrieves those objects from the containers without dropping them after each new operation.
9. It usually occurs when a large file is opened or too much data is taken with the database at a time, resulting in an Out Of Memory Error. In this case, the maximum data volume is calculated, set the minimum and maximum memory space values.
10. Use the finalize function as little as possible, because finalize () will increase the GC workload, and GC is equivalent to consuming the system's computing power.
11. Do not use hash Tables excessively. Developers with certain development experience often use hash tables (one implementation of hash tables in JDK is HashMap) to cache some data, this improves the system running speed. For example, HashMap is used to cache some basic materials such as material information and personnel information, which increases the system speed and memory usage, especially when there are many cached materials. In fact, we can use the cache concept in the operating system to solve this problem, that is, allocate a certain size of cache container to the cached container, objects that do not need to be cached are eliminated according to certain algorithms. On the one hand, the system's operation efficiency will be improved because the cache container is not expanded without limit, this reduces the system memory usage. There are many open-source cache implementation projects, such as ehcache and oscache. These projects all implement common cache algorithms such as FIFO and MRU.