Android garbage collection mechanism

Source: Internet
Author: User

1. The core idea of garbage collection algorithm

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) can use basic type such as Int,long, do not Integer,long object

A basic type variable consumes much less memory resources than the corresponding object, and it is best to use basic variables if it is not necessary.

(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.

4. What if you determine that an object is "junk"?

Since the garbage collector's task is to reclaim the space occupied by garbage objects for use by new objects, how does the garbage collector determine that an object is "junk"? -that is, by what means an object can be recycled.

4.1 Reference Counting algorithm

In Java, it is associated with an object by reference, that is, if you want to manipulate the object, you must do so by reference. So, obviously, a simple way is to determine whether an object can be recycled by reference counting. Without losing its generality, if an object does not have any references associated with it, then the object is basically unlikely to be used elsewhere, and the object becomes a recyclable object. This approach becomes the reference counting method .

This approach is characterized by simplicity and high efficiency, but it does not solve the problem of circular references , so this is not the case in Java (Python uses the reference notation).

1  Public classMain {2      Public Static voidMain (string[] args) {3MyObject Object1 =NewMyObject ();4MyObject Object2 =NewMyObject ();5          6Object1.object =Object2;7Object2.object =Object1;8          9Object1 =NULL;TenObject2 =NULL; One     } A } -   - classmyobject{ the      PublicObject object =NULL; -}

The last two sentences assign Object1 and object2 null, which means that object1 and object2 are no longer accessible, but because they reference each other and cause their reference count to be 0, the garbage collector never recycles them.

In order to solve this problem, the accessibility analysis method was adopted in Java. The basic idea of this method is to search by a series of "GC Roots" objects as a starting point, if there is no unreachable path between "GC Roots" and an object, it is said that the object is unreachable, but it is important to note that objects that are judged to be unreachable do not necessarily become recyclable objects. An object that is judged unreachable must undergo at least two marking processes to become a recoverable object, and if it is still not possible to escape from being a recyclable object during these two marks, it is essentially a recyclable object.

4.2 Accessibility Analysis algorithm

The mainstream implementation of the mainstream Business programming language (Java, C #, and even the old Lisp mentioned earlier) is called the reachability analysis to determine whether an object survives. The basic idea of this algorithm is to use a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, the path of the search is called the reference chain (Reference Chain), when an object to the GC Roots no reference chain is connected (in the words of graph theory, that is, from the GC roots to the object unreachable), it proves that this object is not available. Objects in a virtual machine are recycled if they are unreachable for GC roots nodes.

4.3 example

Let's look at an example:

1 New Object (); 2 New Object (); 3 New Object (); 4 aobj = bobj; 5 aobj = cobj; 6 NULL ; 7 null;

The first few lines are likely to make an object a recyclable object? The code in line 7th causes the object to become recyclable.

Let's look at an example:

1 New String ("Hello"); 2 New Softreference<string> (new String ("java")); 3 New Weakreference<string> (new String ("World"));

Which of these three sentences makes a string object a recyclable object? The 2nd sentence and the 3rd sentence, the 2nd sentence the string object will be judged as a recyclable object in the case of insufficient memory, and the 3rd clause can be judged as a recyclable object under any circumstances.

Summary--Finally, summarize the more common cases where objects are judged to be recyclable:

1) Reference null: assigns a reference to null or points a reference that has already pointed to an object to a new object, such as the following code:

1 New Object (); 2 NULL ; 3 New Object (); 4 New Object (); 5 obj1 = obj2;

2) Local reference: The object that the local reference refers to, such as the following code:

1 void Fun () {2  3 ..... 4      for (int i=0;i<10;i++) {5         New Object (); 6         System.out.println (Obj.getclass ()); 7     }   8 }

Each time the loop finishes executing, the resulting object object becomes a recyclable object.

3) Weak references: Only weak references to objects associated with them, such as:

1 weakreference<string> wr = new weakreference<string> (new String ("World" ));

5, the typical garbage collection algorithm5.1 mark-sweep (marker-purge) algorithm

This is the most basic garbage collection algorithm, the reason is that it is the most basic because it is the easiest to achieve, the idea is the simplest. The tag-purge algorithm is divided into two stages: the tagging phase and the purge phase. The task of the tagging phase is to mark out all objects that need to be recycled, and the purge phase is to reclaim the space occupied by the tagged objects. The exact process is as follows:

It is easy to see that the tag-purge algorithm is easier to implement, but one of the more serious problems is that it is prone to memory fragmentation, and too many fragments can cause the subsequent process to allocate space for large objects without finding enough space to trigger a new garbage collection action ahead of time.

5.2 Copying (copy) algorithm

In order to solve the defect of mark-sweep algorithm, the copying algorithm is proposed. It divides the available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is used up, copy the surviving object to another piece, and then clean up the used memory space once, so the memory fragmentation problem is not easy. The exact process is as follows:

This algorithm is simple, efficient, and not prone to memory fragmentation, but it has a high cost of using memory space because it can use less memory than half the original.

Obviously, the efficiency of the copying algorithm is very much related to the number of surviving objects, if there are many surviving objects, then the efficiency of the copying algorithm will be greatly reduced.

5.3 Mark-compact (marker-collation) algorithm

In order to solve the defect of copying algorithm and make full use of memory space, the mark-compact algorithm is proposed. The algorithm marks the same stage as Mark-sweep, but after the token is completed, it does not clean the recyclable object directly, but instead moves the surviving object to one end and then cleans up memory outside the end boundary. The exact process is as follows:

  

5.4 Generational Collection (generational collection) algorithm

The generational collection algorithm is the algorithm used by most of the JVM's garbage collectors today. Its core idea is to divide the memory into several different regions based on the life cycle of the object's survival. In general, the heap zoning is divided into the old age (tenured Generation) and the New Generation (young Generation), the characteristics of the old age is that each garbage collection only a small number of objects need to be recycled, and the new generation is characterized by a large number of objects to be recycled each time the garbage collected, Then we can take the most suitable collection algorithm according to the characteristics of different generations.

At present, most of the garbage collectors take the copying algorithm for the new generation, because each garbage collection in the Cenozoic has to reclaim most of the objects, that is, the number of operations that need to replicate is less, but the actual is not in accordance with the ratio of 1:1 to divide the new generation of space, In general, the Cenozoic is divided into a larger Eden space and two smaller survivor space, each time using Eden space and one of the survivor space, when recycling, Copy objects that are still alive in Eden and survivor to another survivor space, and then clean up Eden and the survivor space you just used.

Because of the characteristics of the old age is that each recycling only a small number of objects, the general use of the mark-compact algorithm.

Note that there is another generation outside the heap that is the permanent generation (permanet Generation), which is used to store class classes, constants, method descriptions, and so on. The recovery of the permanent generation mainly recycles two parts: obsolete constants and useless classes.

http://blog.csdn.net/wuqiong_524itcast/article/details/25378685

Http://www.cnblogs.com/dolphin0520/p/3783345.html

Android 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.