Java garbage collection mechanism, talk about 1

The garbage collector system has its own set of schemes to determine which memory blocks should be reclaimed and which ones do not meet the requirements and will not be reclaimed temporarily.

The execution of the garbage collector in a Java program is automatic and cannot be enforced. Even if the programmer can clearly determine that a piece of memory is useless and should be recycled, the programmer cannot force the garbage collector to reclaim the memory block. .

The only thing the programmer can do is to "advise" the garbage collector to execute by calling the System.gc method, but it is not known whether or when it will execute.

This is also the main disadvantage of the garbage collector .

Of course, compared with the great convenience it brings to programmers, this disadvantage is not concealed.

The basic principle of GC

Java's memory management == management of objects, including [object allocation, release]

        For programmers, the new keyword is used to allocate objects; when releasing an object, as long as all references to the object are assigned to null, let The program can no longer access this object, we call the object "unreachable". The GC will be responsible for reclaiming the memory space of all "unreachable" objects.

        For the GC, when the programmer creates an object, the GC begins to monitor the address, size, and usage of the object.
        Generally, GC records and manages all objects in the heap in a directed graph manner. Determine which objects are "reachable" and which are "unreachable" in this way
        When the GC determines that some objects are "unreachable", it is the responsibility of the GC to reclaim the memory space.
        However, in order to ensure that GC can be implemented on different platforms, the Java specification does not strictly stipulate many behaviors of GC. For example, there are no clear rules for important issues such as what type of recycling algorithm to use and when to do it. Therefore, implementers of different JVMs often have different implementation algorithms. This also brings many uncertainties to the development of Java programmers

 

The main features of the garbage collector are: 

1. Work goal : Reclaim the memory space of objects that have been useless, so as to avoid the generation of memory leaks, save memory resources, and avoid program code crashes.

2. The garbage collector's criteria for judging whether an object's memory space is useless are :

    If the object can no longer be referenced by any "active part" of the program, then we say that the object's memory space is useless

    Active part: refers to a part of the program that participates in the invocation of the program, is in the process of execution, and has not been executed yet.

    When a method is executed, the local variables in it will go beyond the scope of use, which can be treated as garbage collection at this time, but every time the method is called again in the future,

    The local variables in it will be recreated.

3. Although the garbage collector thread runs as a low-priority thread , it may execute in bursts to save memory resources when the amount of available memory in the system is too low. Of course, its execution is also unpredictable.    
4. The garbage collector can not be enforced , but the programmer can suggest the implementation of the garbage collector by calling the System.gc method.    

5. There is no guarantee that a useless object will be collected by the garbage collector, nor is there any guarantee that the garbage collector will execute in a piece of Java language code.

    Therefore, the memory space allocated during the execution of the program may remain until the execution of the program is completed, unless the space is reallocated or reclaimed by other methods.

    It can be seen that it is impossible to completely eradicate the generation of memory leaks . But don't forget that Java's garbage collector, after all, frees programmers from the heavy lifting of manually reclaiming memory space. Imagine that a programmer wants to write a 100,000-line code in C or C++, then he will fully appreciate the advantages of Java's garbage collector!    

6. There is also no way to predict which of a set of objects that all meet the garbage collector's collection criteria will be collected first .    
7. A circular reference to an object does not affect its collection by the garbage collector.    

8. The garbage collector can be implied to collect an object by initializing its reference variables (handles) to a null value .

    But at this point, if the object has event listeners attached (a typical AWT component), it still cannot be collected. Therefore, before setting a reference variable to a null value, you should pay attention to whether the object pointed to by the reference variable is being monitored. If so, you must first remove the listener before assigning a null value.    

9. Every object has a finalize( ) method, which is inherited from the Object class.    

10. The finalize( ) method is used to reclaim system resources other than memory, such as file handlers and network connectors.

    The order in which the method is called is independent of the order in which the objects used to call the method are created.

    In other words, the order in which the methods are written when the program is written is irrelevant to the order in which the methods are actually called. Note that this is only a feature of the finalize( ) method.    

11. The finalize( ) method can only be called once per object. If an exception occurs during the execution of the finalize( ) method, the object can still be collected by the garbage collector.    
12. The garbage collector keeps track of each object, collects those that are not reachable (that is, the object is not called by any "living part" of the program), and reclaims the memory space it occupies. But during garbage collection, the garbage collector will call the finalize( ) method to "recover" the unreachable object as a reachable object by letting other objects know of its existence. Since the finalize( ) method can only be called once per object, it is only possible for each object to "recover" once. 13. The finalize( ) method can be called explicitly, but it cannot be garbage collected.    14. The finalize( ) method can be overloaded, but only methods that have the characteristics of the original finalize( ) method can be called by the garbage collector.    15. The finalize( ) method of a subclass can explicitly call the finalize( ) method of the superclass as the last appropriate action on an object of that subclass. But the Java compiler doesn't consider this an overriding operation, so it doesn't check the call.    16. When the finalize( ) method has not been called, the System.runFinalization( ) method can be used to call the finalize( ) method and achieve the same effect, garbage collection of useless objects.    17. When a method is executed, its local variables will go beyond the scope of use, which can be treated as garbage collection at this time, but each time the method is called again, the local variables will be recreated. 18.    




    
The Java language uses a "marked swap area garbage collection algorithm". The algorithm traverses the handle of each object in the program, marks the referenced object, and then recycles the object that has not been marked. The so-called traversal can be simply understood as "checking each one". 19. The Java language allows programmers to add a finalize( ) method to any method, which will be called before the garbage collector swaps objects for recycling. But don't rely too much on this method to recycle and reuse system resources, because the execution result after this method is called is unpredictable.    


In short, in the Java language, there are only two criteria for judging whether a memory space meets the garbage collector collection criteria:    
1. The empty value null is assigned to the object, and the following is not called again.    
2. Assigning a new value to an object re-allocates memory space.    
Finally, let me remind again that a piece of memory space complies with the collection standards of the garbage collector, which does not mean that this piece of memory space will definitely be collected by the garbage collector.


The Java language establishes a garbage collection mechanism to track objects in use and find and recycle objects that are no longer used (referenced). This mechanism can effectively prevent two dangers that may occur in dynamic memory allocation: memory exhaustion caused by excessive memory garbage, and illegal memory reference caused by improper memory release.   The core idea of ​​​​the garbage collection algorithm is to identify the objects in the available memory space of the virtual machine, that is, the heap space. If the object is being referenced, it is called a surviving object. On the contrary, if the object is no longer referenced, it is a garbage object. , the space it occupies can be reclaimed for reallocation. The choice of the garbage collection algorithm and the reasonable adjustment of the parameters of the garbage collection system directly affect the system performance, so developers need to have a deeper understanding.   2. The condition of triggering the main GC (Garbage Collector) The     JVM has a high frequency of secondary GC, but because this GC takes up a very short time, it has little impact on the system. What deserves more attention is the trigger condition of the main GC, because it has obvious impact on the system. In general, there are two conditions that trigger the main GC:    ① When the application is idle, that is, when no application threads are running, the GC will be called. Because the GC is performed in the thread with the lowest priority, the GC thread will not be called when the application is busy, except for the following conditions.   ② When the Java heap memory is insufficient, the GC will be called. When the application thread is running and new objects are created during the running process, if the memory space is insufficient at this time, the JVM will forcibly call the GC thread in order to reclaim the memory for new allocation. If the memory allocation requirements cannot be met after one GC, the JVM will perform two more GC attempts for further attempts. If the requirements are still not met, the JVM will report an "out of memory" error and the Java application will stop. 
 

 


 

 

 

  Since whether to perform the main GC is decided by the JVM according to the system environment, and the system environment is constantly changing, the operation of the main GC is uncertain, and it is impossible to predict when it will inevitably appear, but it can be determined for a long-running application. In other words, its main GC is repeated.  


  3. Measures to reduce GC overhead 
 
  According to the above GC mechanism, the operation of the program will directly affect the changes of the system environment, thus affecting the triggering of the GC. If it is not designed and coded for the characteristics of GC, there will be a series of negative effects such as memory residency. To avoid these effects, the basic principle is to minimize garbage and reduce the overhead of the GC process. The specific measures include the following aspects: 
 
  (1) Do not explicitly call System.gc() 
 
  This function recommends the JVM to perform the main GC, although it is only a recommendation but not a requirement, but in many cases it will trigger the main GC, thereby increasing the main GC. frequency, which increases the number of intermittent pauses.  
  (2) Minimize the use of 
 
  temporary objects. After jumping out of the function call, temporary objects will become garbage. Less use of temporary variables is equivalent to reducing the generation of garbage, thereby prolonging the time for the second trigger condition to appear, reducing Chance of main GC.  
  (3) It is best to explicitly set the object to Null when it is not in use. 
 
  Generally speaking, the object that is Null will be treated as garbage, so explicitly set the unused object to Null, which is conducive to the GC collector to determine garbage, thus improving the GC efficiency. 
 
  (4) Try to use StringBuffer instead of String to accumulate strings (see another blog article, String and StringBuffer in Java). 
 
  Since String is a fixed-length string object, when accumulating String objects, it is not expanded in a String object. Increase, but re-create a new String object, such as Str5=Str1+Str2+Str3+Str4, multiple garbage objects will be generated during the execution of this statement, because a new String must be created for each "+" operation objects, but these transition objects are meaningless to the system and will only add more garbage. To avoid this situation, you can use StringBuffer instead to accumulate strings. Because StringBuffer is variable in length, it expands on the original basis without generating intermediate objects.  
  (5) If you can use basic types such as Int and Long, you don't need Integer and Long objects. The memory resources occupied by basic type variables are much less than the corresponding objects. If it is not necessary, it is better to use basic variables. 
 
  (6) Minimize the use of static object variables 
 
  Static variables are global variables and will not be recycled by GC, they will always occupy memory. 
 
  (7) The time of creation or deletion of decentralized objects  

  Concentrating on creating a large number of new objects in a short period of time, especially large objects, will suddenly require a large amount of memory. When the JVM faces this situation, it can only perform main GC to reclaim memory or integrate memory fragments, thereby increasing the frequency of main GC. . Centrally delete objects, the reason is the same. It makes a large number of garbage objects suddenly appear, and the free space is bound to decrease, thereby greatly increasing the chance of forcing the main GC the next time a new object is created.  


5. Java memory leaks 
 
  Due to the garbage collection mechanism, any unreachable object (object no longer referenced) can be reclaimed by the garbage collection thread. Therefore, what is commonly referred to as a Java memory leak actually refers to unintentional, unintentional object references, or unintentional object retention. Unintentional object reference refers to the fact that the developer of the code has already used the object, but accidentally saves a reference to the object due to a coding error (the existence of this reference is not the subjective will of the coder), thus making the object It has been unable to be reclaimed by the garbage collector. This space that was originally thought to be released but was finally not released can be considered to be "leak".  
  Consider the following program, in the ObjStack class, uses the push and pop methods to manage objects on the stack. The index in both methods is used to indicate the next available position on the stack. The push method stores a reference to the new object and increments the index value, while the pop method decrements the index value and returns the top element on the stack. In the main method, a stack with a capacity of 64 is created, and the push method is called 64 times to add objects to it. At this time, the value of index is 64, and then the pop method is called 32 times, the value of index becomes 32, and the stack is popped. Means the space in the stack should be collected. But in fact, the pop method just decrements the index value, and the stack still holds references to those objects. Therefore, 32 useless objects will not be reclaimed by GC, resulting in memory leakage.


Through the above understanding of the characteristics of the garbage collector, you should be able to clarify the role of the garbage collector and the criteria for the garbage collector to judge whether a memory space is useless. Simply put, when you assign null to an object and redirect the object's referrer, the object is eligible for the garbage collector.    
Judging whether an object complies with the garbage collector's collection standards is an important test site for the garbage collector part of the SUN programmer certification exam (it can be said that this is the only test site). Therefore, candidates in a given piece of code should be able to determine which objects meet the criteria for garbage collector collection and which ones do not. The following is a detailed explanation of the question types that may appear in several certification exams:    
Object obj = new Object ( )     
We know that obj is a handle of Object. When the new keyword appears, memory space is allocated to the newly created object, and the value of obj is the first address of the newly allocated memory space, that is, the value of the object (please note that the value of the object and the content of the object have different meanings two concepts: the value of the object refers to the first address of its memory block, that is, the handle of the object; and the content of the object is its specific memory block). At this time, if obj = null; then the memory block pointed to by obj is useless at this time, because the variable is not called again.    
Please look at the following three types of questions that may appear in the certification exam:    
Program segment 1:    
1. fobj = new Object ( )     
2. fobj.Method ( )     
3. fobj = new Object ( )     
4. fobj.Method ( )     
Q: In this code, which line of fobj meets the garbage collector's collection criteria?    
Answer: Line 3. Because the fobj in line 3 is assigned a new value, a new object is generated, that is, a new memory space is replaced, which is also equivalent to assigning a null value to fobj in line 1. This type of question is the easiest on the Certification 0 exam.    
Block 2:    
1. Object sobj = new Object ( )     
2. Object sobj = null    

3. Object sobj = new Object ( )     
4. sobj = new Object ( )     
Q: In this code, which line of memory space meets the garbage collector's collection standard?    
Answer: Lines 1 and 3. Because line 2 assigns null to sobj, sobj in line 1 here meets the collection criteria of the garbage collector. And line 4 is equivalent to assigning null to sobj, so the sobj in line 3 here also conforms to the collection standard of the garbage collector.    
If there is a handle a of an object, and you use a as a parameter of a constructor,
that is, when new Constructor ( a ), even if you assign a value of null to a, a does not meet the collection criteria of the garbage collector. a cannot be collected by the garbage collector until the new object constructed by the above constructor is assigned a null value.    
Block 3:    
1. Object aobj = new Object ( )     
2. Object bobj = new Object ( )     
3. Object cobj = new Object ( )     
4.
5. aobj = bobj;    aobj = cobj;    
6.
7. cobj = null;    aobj = null;    
Q: In this code, which line of memory space meets the collection standard of the garbage collector?    
Answer: Line 7. Note that this type of question is the most difficult type you may encounter on a certification exam.    
Lines 1-3 create three objects of the Object class: aobj, bobj, and cobj.    
Line 4: At this time, the handle of the object aobj points to bobj, so the execution of this line cannot make aobj meet the collection standard of the garbage collector.    
Line 5: At this time, the handle of the object aobj points to cobj, so the execution of this line cannot make aobj meet the collection standard of the garbage collector.    

Line 6: At this point, none of the objects are eligible for the garbage collector.    
Line 7: The object cobj complies with the collection criteria of the garbage collector because the handle of cobj points to a single address space. In line 6, cobj has been assigned to null, but cobj also points to aobj (line 5), so cobj does not meet the collection standards of the garbage collector at this time. In line 7, the address space pointed to by aobj is also assigned a null value, which means that the address space pointed to by cobj has been completely assigned a null value. So at this time cobj finally meets the collection standards of the garbage collector. But for aobj and bobj, it is still impossible to judge whether they meet the collection criteria. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325984232&siteId=291194637
Recommended