Android garbage collection mechanism and program optimization system.gc_android

Source: Internet
Author: User
Tags garbage collection memory usage stringbuffer

1. The core idea of garbage collection algorithm

The Java language establishes a garbage collection mechanism for tracking objects that are in use and for discovering and reclaiming objects that are no longer in use (references). This mechanism can effectively guard against the two risks that may occur in dynamic memory allocation: the memory exhaustion caused by excessive memory garbage, and an illegal memory reference caused by improper memory release.

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

2. Conditions that trigger the main GC (garbage Collector)

The JVM has a high frequency of GC, but because the GC takes a very short time, it has little impact on the system. What is more noteworthy is the trigger condition of the primary GC, because it has an obvious effect on the system. In general, there are two conditions that trigger the primary GC:
① GC is invoked when the application is idle, that is, no application thread is running. Because the GC is in the lowest-priority thread, the GC thread is not invoked when the application is busy, except for the following conditions.

The GC is invoked 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 is forced to call the GC thread to reclaim the memory for the new assignment. If the GC is not able to meet the requirements of memory allocation after the first time, the JVM will do two more GC for further attempt, if still unable to meet the requirements, the JVM will report "Out of Memory" error, the Java application will stop.

Because the main GC is determined by the JVM based on 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 the main GC is repeated for a long-running application.

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. If you do not design and encode the characteristics of GC, there will be a series of negative effects such as memory presence. To avoid these effects, the basic principle is to minimize 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 be the primary GC, although it is recommended rather than certain, but in many cases it triggers the primary GC, which increases the frequency of the primary GC, and increases the number of intermittent pauses.

(2) Minimizing the use of temporary objects

The temporary object becomes garbage after the function call is dropped, and the less temporary variable is the equivalent of reducing garbage generation, thus prolonging the occurrence of the second triggering condition mentioned above and reducing the chance of the primary GC.

(3) It is best to explicitly null an object when it is not in use

In general, NULL objects are treated as garbage, so it is more efficient for GC collectors to determine garbage by explicitly setting unused objects to null.

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

Because string is a fixed-length string object, accumulating a string object is not amplified in a string object, but rather creates a new string object, such as STR5=STR1+STR2+STR3+STR4, that produces multiple garbage objects during execution. Because a new string object must be created for the secondary "+" operation, these transition objects are meaningless to the system and will only add more garbage. To avoid this situation, you can use StringBuffer to accumulate strings, because the StringBuffer is variable length, it expands on the original basis, does not produce intermediate objects.

(5) can use basic type such as Int,long, do not use Integer,long object

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

(6) Use of static object variables as little as possible

Static variables are global variables and are not reclaimed by GC, and they can occupy memory all the time.

(7) Time to create or delete dispersed objects

Focusing on a large number of new objects in a short time, especially large objects, can result in a sudden need for large amounts of memory, which, in the case of the JVM, can only be primary GC to reclaim memory or consolidate memory fragmentation, thereby increasing the frequency of the primary GC. The same is true for deleting objects centrally. It causes a sudden emergence of a large number of garbage objects, the inevitable reduction of free space, thereby greatly increasing the next time to create a new object to force the main GC opportunity.

-------------------------------------------------------------

Many people attribute Java's "inefficiency" to the inability to manage memory freely, but we also know that the benefits of encapsulating memory management are not.

The memory allocations in Java are implemented with a new object, which is simple, and there are some mechanisms to "improve" memory recycling, the most conspicuous of which is the System.GC () function.

At first glance this function seems to be garbage collected, but the fact is not so simple.

The purpose of this GC () function is simply to remind the virtual machine that the programmer wants a garbage collection. However, it does not guarantee that garbage collection will be carried out, and exactly when it depends on the specific virtual machine, different virtual machines have different countermeasures.

So the next question is: what is the criteria for GC () for recycling? In other words, what kind of object can be recycled?

In simple terms, there is no object that is pointed to by any of the available variables. I've invented this, and ... It means to be able to find, what kind of is not up to?

For example:

A.V = b;
B.V = C;
/*
*watch out!
* *
a.v = D;

Take a look at this piece of code:

First line: Object A's variable v is pointing to object B
Second line: Object B's Variable v is pointing to object C
Line six: Object A's variable v is pointing to the variable d.

This time, although the variable C point to the object has C and B.V point to it, but they are not up to, why? Because the only thing that can find them is A.V, but now the A.V point to D, so they are not up to it.
The reason is also very intuitive: there is no accessible variable point to you, you still have the reason to live? Who can find you if you live?

So, in C + +, the habit of leaving the freed pointer to null is preserved in Java, because it's probably the only way you can release memory.

The last maxim: do not use GC functions frequently.

Finally give you a reason why you need GC

The application's operations on resources are usually simply divided into the following steps:

1, allocating memory for the corresponding resources

2. Initialize Memory

3, the use of resources

4, clean up the resources

5, free memory

The way that an application manages resources (memory usage) is common in general as follows:

1, Manual management: c,c++

2, Count Management: COM

3. Automatic Management: ... net,java,php,go ...

However, the complexity of manual management and count management can easily lead to the following typical problems:

1. Programmers forget to release memory

2. The application accesses the memory that has been freed

The consequences are very serious, common such as memory leaks, data content garbled, and most of the time, the behavior of the program will become weird and unpredictable, as well as access violation.

The solution given in. NET, Java, and so on, is memory management through the automated garbage collection mechanism GC. In this way, question 1 is resolved naturally, and question 2 does not have a basis for existence.

Summary: Unable to automate the memory management method is very easy to produce bugs, affecting system stability, especially on-line multiple server cluster environment, the program occurs when the bug must be positioned to a server and then dump memory to analyze the bug, extremely hit the developer programming enthusiasm, And a steady stream of similar bugs is disgusting.

Related Article

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.