Java garbage collection mechanism

Source: Internet
Author: User
Tags event listener

The garbage collector system has its own set of programs to determine which memory block should be recycled, which is not eligible for temporary recovery. The garbage collector's execution 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, and the programmer cannot force the garbage collector to reclaim that block of memory. The only thing programmers can do is by calling system. GC method to "recommend" the execution of the garbage collector, but whether it can be executed, and when execution is not known. This is also the main drawback of the garbage collector. Of course, this drawback is his flaws relative to the great convenience it brings to the programmer.

The main features of the garbage collector are:

1. The garbage collector's goal is to reclaim the memory space of objects that are already useless, thus avoiding the generation of memory leaks, saving memory resources and avoiding program code crashes.

2. The standard for the garbage collector to determine whether an object's memory space is useless is if the object is no longer referenced by any of the "active parts" of the program, and at this point we say that the object's memory space is useless. The so-called "part of the activity", refers to a part of the program to participate in the program calls, is executing the process, has not been completed.

When a method executes, the local variable goes out of scope and can be garbage collected, but the local variables are recreated each time the method is called again.

3. Although the garbage collector thread is running as a low-priority thread, it may execute suddenly to save memory resources when the system is too low-available. Of course, its execution is unpredictable.
4. The garbage collector cannot be enforced, but programmers can call system. GC method to recommend that the garbage collector be executed.
5. There is no guarantee that a useless object will be collected by the garbage collector or that the garbage collector will be executed in a Java language code. Therefore, the memory space allocated during program execution may persist until the program executes, unless the space is reassigned or reclaimed by another method. This shows that it is impossible to completely eradicate the generation of memory leaks. Don't forget, though, that Java's garbage collector frees programmers from the heavy work of manually reclaiming memory space. Imagine a programmer using C or C + + to write a 100,000-line statement of code, then he will be fully aware of the Java garbage collector's advantages!
6. There is also no way to predict which one will be collected first in a set of objects that meet the garbage collector collection criteria.
7. A circular Reference object does not affect its collection by the garbage collector.

8. You can imply that the garbage collector collects the object by initializing its reference variable (reference variables, the handle handles) to a null value. At this point, however, if the object is connected to an event listener (a typical AWT component), it cannot be collected. Therefore, before setting a reference variable to a null value, you should be aware that the reference variable points to the object is listening, if so, to remove the listener first, then you can assign a null value.
9. Each 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, like file processors and network connectors. The order in which the methods are called is irrelevant to the order in which the objects used to invoke the method are created. In other words, the order of the method and the actual invocation order of the method are irrelevant when the program is written. Please note that this is only a feature of the Finalize () method.
11. Each object can only call the Finalize () method one time. If an exception (exception) is generated when the Finalize () method executes, the object can still be collected by the garbage collector.
12. 13. The Finalize () method can be explicitly called, but it cannot be garbage collected.    
14. The Finalize () method can be overloaded (overload), but only methods with the original finalize () method characteristics can be called by the garbage collector.    
15. The Finalize () method of the subclass can explicitly call the Finalize () method of the parent class as the last appropriate action for that subclass object. However, the Java compiler does not consider this to be an overwrite operation (overriding), so it does not check its invocation.    
16. System when the Finalize () method has not been called. The Runfinalization () method can be used to invoke the Finalize () method and achieve the same effect of garbage collection on useless objects.    
17. 18. java language uses a "garbage collection algorithm for the tag swap area." The algorithm iterates through the handle of each object in the program, marks the referenced object, and then reclaims the object that has not yet 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 that is called before the garbage collector swaps the objects. However, do not rely too much on this method to recycle and reuse system resources because the execution results after the method invocation are unpredictable.


In summary, in the Java language, there are only two criteria that determine whether a piece of memory space conforms to the garbage collector collection criteria:
1. A null value was given to the object, and the following has not been called.
2. A new value is assigned to the object, and the memory space is redistributed.
Finally, again, a memory space that meets the collection criteria of the garbage collector does not necessarily mean that the memory space will be collected by the garbage collector.


The Java language establishes a garbage collection mechanism to keep track of objects being used and to discover and reclaim objects that are no longer used (referenced). This mechanism can effectively protect against the two dangers that can occur in dynamic memory allocation: memory exhaustion caused by excessive memory garbage, and improper memory release caused by illegitimate references.

The core idea of the garbage collection algorithm is to recognize the available memory space of the virtual machine, that is, the object in the heap space, if the object is being referenced, then call it a living object, conversely, if the object is no longer referenced, then it is garbage object, it can reclaim the space occupied by it for redistribution. The choice of garbage collection algorithm and the reasonable adjustment of garbage collection system parameters directly affect the system performance, so it is necessary for developers to do more in-depth understanding.

2. Conditions that trigger the main GC (garbage Collector)
The JVM has a high frequency of secondary GC, but because this GC occupies a very short time, it has little effect on the system. More notable is the trigger condition of the main GC, because it has a noticeable effect on the system. Overall, there are two conditions that trigger the main GC:

① The GC is called when the application is idle, that is, when no application thread is running. Because the GC is in the lowest priority thread, the GC thread is not called when the application is busy, except for the following conditions.

GC is called when the ②java heap is low on memory. When the application thread is running and a new object is created during the run, if there is not enough memory space, the JVM will forcibly invoke the GC thread to reclaim the memory for the new allocation. If the GC still fails to meet the memory allocation requirements after one time, the JVM will take another two GC for further attempts, and if it still fails to meet the requirements, the JVM will report an "out of memory" error and the Java application will stop.

Since the main GC is determined by the JVM in terms of the system environment, and the system environment is constantly changing, the main GC runs with uncertainty and cannot predict when it will inevitably occur, but it can be determined that for a long-running application, 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 system environment changes, thus affecting the GC trigger. Without design and coding for GC features, there is a series of negative effects such as memory presence. To avoid these effects, the basic principle is to minimize the garbage and reduce the cost of the GC process as much as possible. Specific measures include the following:

(1) Do not explicitly call System.GC ()

This function recommends that the JVM perform the main GC, although it is only recommended, but not necessarily, but in many cases it triggers the main GC, increasing the frequency of the main GC, which increases the number of intermittent pauses.
(2) Minimizing the use of temporary objects

Temporary objects will become garbage after jumping out of function calls, and less temporary variables will be equivalent to reducing garbage generation, thus prolonging the occurrence of the second triggering condition mentioned above and reducing the chance of the main GC.
(3) It is best to explicitly set NULL when an object is not used

In general, NULL objects are treated as garbage, so explicitly setting unused objects to NULL is useful for GC collectors to determine garbage, which increases the efficiency of the GC.

(4) Try to use StringBuffer instead of string to accumulate strings (see blog Another article in Java, String and StringBuffer)

Because string is a fixed-length string object, when the string object is accumulated, it is not amplified in a string object, but instead re-creates a new string object, such as STR5=STR1+STR2+STR3+STR4, which produces multiple garbage objects during the execution of the statement. Because a new string object must be created for the "+" operation, these transition objects are meaningless to the system and only add more garbage. Avoid this situation can use StringBuffer to accumulate the string, because the StringBuffer is variable long, it expands on the original basis, does not produce intermediate objects.
(5) Using basic types such as Int,long, it is not necessary to use the Integer,long object basic type variables to occupy more memory resources than the corresponding objects occupy much less, if not required, it is best to work with basic variables.

(6) Minimize the use of static object variables

Static variables are global variables, are not recycled by GC, and they always consume memory.

(7) time when the object was created or deleted
Concentrating on creating new objects in a short amount of time, especially large objects, can result in a sudden need for a lot of memory, and in this case the JVM can only perform a primary GC to reclaim memory or consolidate memory fragments, thereby increasing the frequency of the main GC. The same is true for deleting objects centrally. It makes a large number of garbage objects suddenly appear, and the free space inevitably decreases, which greatly increases the chance of forcing the main GC the next time the new object is created.
5.Java memory leaks

Because of the garbage collection mechanism, any unreachable objects (objects that are no longer referenced) can be reclaimed by the garbage collector thread. So the usual Java memory leak actually refers to an unconscious, unintentional object reference, or an unconscious object being persisted. The unconscious object reference refers to the fact that the developer of the code has already used the object, but has accidentally saved a reference to the object because of a coded error (the existence of this reference is not a subjective intention of the coder), so that the object has not been reclaimed by the garbage collector. This space, which was supposed to be released but eventually failed to be released, could be thought of as being "leaked".
Consider the following program, in the Objstack class, using the push and pop methods to manage objects in the stack. The index in two methods is used to indicate the next available location in the stack. The push method stores a reference to the new object and increases the index value, while the Pop method decreases the index value and returns the topmost element of the stack. In the main method, a stack with a capacity of 64 is created, and 64 calls to the push method to add objects to it, when the value of index is 64 and then 32 calls the Pop method, the value of index becomes 32, and the stack means that the space in the stack should be collected. But in fact, the pop method simply reduces the index value, and the stack still maintains a reference to those objects. Therefore, 32 useless objects are not recycled by GC, resulting in memory leaks.


By understanding the characteristics of the garbage collector above, you should be able to identify the role of the garbage collector, and the garbage collector to determine whether a piece of memory space is useless standard. Simply put, when you assign a value of NULL to an object and redirect the object's reference, the object conforms to the garbage collector's collection criteria.
Determine if an object meets the collection criteria of the garbage collector, which is an important test point for the garbage collector part of the Sun's Programmer certification exam (This is the only testing center, to say the point). Therefore, candidates in a given code, should be able to determine which object conforms to the garbage collector standard, which does not meet. The following combination of several certification exams may appear in the specific types of questions to explain:
Object obj = new Object ()
We know that obj is a handle to object. When the new keyword is present, the newly created object is allocated a memory space, and the value of obj is the first address of the newly allocated memory space, that is, the value of the object (note, in particular, that the value of the object and the object's contents are two concepts of different meanings: The object's value is the first address of its memory block, the , and the object's content is its specific block of memory). If there is obj = null at this point, then the memory block that obj points to is useless at this point because the variable is not called again.
Please look at the following types of questions that may appear in the three certification exams:
Program Segment 1:
1. Fobj = new Object ()
2. Fobj. Method ()
3. Fobj = new Object ()
4. Fobj. Method ()
Q: In this code, the fobj of the first few lines meet the garbage collector's collection criteria?
Answer: Line 3rd. Because the fobj of line 3rd is assigned a new value, a new object is created, that is, a new memory space is replaced, and a null value is assigned to the Fobj in line 1th. This type of question is the simplest in the certification 0 exam.
Program Segment 2:
1. Object sobj = new Object ()
2. Object sobj = null

3. Object sobj = new Object ()
4. Sobj = new Object ()
Q: In this code, the memory space of the first few lines is in compliance with the garbage collector's collection criteria?
Answer: Lines 1th and 3rd. Because the 2nd behavior sobj assignment is null, the sobj on this 1th line conforms to the garbage collector's collection criteria. The 4th line is equivalent to sobj assignment null, so the sobj on this 3rd line also conforms to the garbage collector's collection criteria.
If you have a handle to a object and you use a as a parameter to a constructor,
When you are new Constructor (a), even if you assign a value of null,a, it does not meet the collection criteria of the garbage collector. A cannot be collected by the garbage collector until a new object constructed by the above constructor is assigned a null value.
Program Segment 3:
1. Object aobj = new Object ()
2. Object bobj = new Object ()
3. Object cobj = new Object ()
4. Aobj = Bobj;
5. Aobj = CObj;
6. CObj = null;
7. Aobj = null;
Q: In this code, the memory space of the first few lines is in compliance with the garbage collector's collection criteria?
Answer: Line 7th. Note that this type of question is the most difficult question you might encounter in a certification exam.
Line 1-3 creates three objects of the object class, respectively: Aobj,bobj,cobj
Line 4: The handle to the object aobj at this point is bobj, so the execution of the row does not allow aobj to conform to the collection criteria of the garbage collector.
Line 5: The handle to the object aobj at this point is cobj, so the execution of the row does not allow aobj to conform to the collection criteria of the garbage collector.

Line 6: There are still no objects that meet the garbage collector's collection criteria.
Line 7: Object CObj conforms to the garbage collector's collection criteria because the CObj handle points to a single address space. In line 6th, CObj has been assigned null, but the CObj also points to Aobj (line 5th), so CObj does not meet the garbage collector's collection criteria at this time. In line 7th, the address space pointed to by Aobj is also given a null value, which means that the address space pointed to by CObj has been completely assigned a null value. So at this point the CObj finally meets the collection criteria for the garbage collector. However, for Aobj and Bobj, it is still not possible to determine whether they meet the collection criteria.

Java garbage collection mechanism

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.