Android Garbage collection mechanism and program optimization ES1en.ES2en

  • 2020-12-13 19:04:57
  • OfStack

1. The core idea of garbage collection algorithm

The Java language establishes a garbage collection mechanism to track objects in use and to find and reclaim objects that are no longer in use (references). This mechanism can effectively guard against two possible dangers in dynamic memory allocation: memory depletion due to excessive memory garbage, and illegal memory references due to improper memory release.

The core idea of the garbage collection algorithm is to identify the objects in the free memory space of the virtual machine, namely the heap space. If the object is being referenced, it is called a living object; otherwise, if the object is no longer referenced, it is called a garbage object, and the space occupied by it can be reclaimed for redistribution. The choice of garbage collection algorithm and the reasonable adjustment of garbage collection system parameters directly affect the performance of the system, so developers need to have a deeper understanding.

2. Conditions that trigger the master GC(Garbage Collector)

JVM carries out GC with high frequency, but this KIND of GC occupies very short time, so it has little impact on the system. Of greater concern is the trigger condition of the master GC, as it has a significant impact on the system. In summary, there are two conditions that trigger GC:
GC is called when the application is idle, that is, when no application threads are running. Because GC is in the lowest-priority thread, the GC thread is not invoked when the application is busy, except for the following conditions.

Java heap is not enough memory,GC will be called. When the application thread is running and creates a new object while it is running,JVM forces the GC thread to be called in order to reclaim memory for the new allocation. If GC1 fails to meet the memory allocation requirement,JVM will make two further attempts at GC. If it fails to meet the requirement, JVM will report an error of "out of memory" and the Java application will stop.

As the operation of the master GC is determined by JVM according to the system environment, which is constantly changing, the operation of the master GC is uncertain, and it is impossible to predict when it will inevitably occur. However, it is certain that for a long-term running application, the master GC is repeated.

3. Measures to reduce GC costs

According to the above MECHANISM of GC, the operation of the program will directly affect the change of system environment, thus affecting the trigger of GC. If GC is not designed and coded for its characteristics, there will be a series of negative effects such as memory residence. To avoid these effects, the basic principle is to minimize garbage and reduce overhead in the GC process. Specific measures include the following aspects:

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

This function advises JVM to proceed to GC. Although it is only a suggestion rather than a fixed one, in many cases it will trigger GC to increase the frequency of GC and thus increase the number of intermittent pauses.

(2) Minimize the use of temporary objects

Temporary objects become garbage when they jump out of a function call. Reducing the use of temporary variables reduces the garbage generation, thus lengthening the time for the second trigger above and reducing the chance of the primary GC.

(3) It is better to explicitly set the object to Null when it is not in use

1 Generally speaking, objects that are Null will be treated as garbage, so explicitly setting unused objects as Null is conducive to the determination of garbage by the GC collector, thus improving the efficiency of GC.

(4) Try to use StringBuffer instead of String to accumulate strings (see String and StringBuffer in another article JAVA for details)

Because String is fixed long string objects, accumulative String object, not in a String object amplification, but to create new String object, such as Str5 = Str1 + Str2 + Str3 + Str4, during the implementation of this statement will produce more garbage objects, because the time for operation on the "+" must create a new String objects, but these transitional object for the system is of no practical significance, will only add more junk. To avoid this situation, StringBuffer can be used to accumulate strings instead. Since StringBuffer is variable in length, it expands on the original basis without producing intermediate objects.

(5) Use basic types such as Int,Long, instead of Integer,Long objects

Base-type variables take up much less memory resources than their corresponding objects, and it is best to use them if they are not necessary.

(6) Minimize the use of static object variables

Static variables belong to global variables and will not be reclaimed by GC, they will consume memory directly.

(7) Scatter the time of object creation or deletion

A large number of new objects, especially large objects, will be created in a short period of time, resulting in the sudden need for a large amount of memory. When FACED with this situation,JVM can only carry out master GC to reclaim memory or consolidate memory fragments, thus increasing the frequency of master GC. The same is true for deleting objects in a set. It makes a lot of garbage objects suddenly appear and the free space must be reduced, thus greatly increasing the chance of forcing the master GC the next time a new object is created.

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

Many people blame the "inefficiency" of Java on not being able to manage memory freely, but we also know the benefits of encapsulating memory management, and we won't go into that here.

The memory allocation in Java is implemented with new1 new objects. This is simple, and there are several mechanisms for "improving" memory recovery, the most obvious of which is the ES128en.gc () function.

At first glance, this might seem like a garbage collector, but it's not that simple.

The gc() function is really just a reminder to the virtual machine that the programmer wants to garbage collect once. But it does not guarantee that garbage collection 1 will take place, and the exact timing depends on the specific virtual machine, and different virtual machines have different countermeasures.

So the next question is: What are the guidelines for gc() recycling? So what kind of objects can be recycled?

Simply put: an object that is not pointed to by any reachable variable. I invented the koda here... That means to be found, but what is not reachable?

Such as:


a.v = b;
b.v = c;
/*
*Watch out !
*/
a.v = d;

Take a look at this code:

Line 1: Object a's variable v points to object b
Line 2: Object b's variable v points to object c
Line 6: The variable v for object a points to the variable d.

At this point, although the variable c points to objects like c and b.v point to it, they are not reachable anymore. Why? Because the only one that can find them is a.v, but now a.v points to d, so they are unreachable.
The reason is straightforward: with no accessible variables pointing at you, do you still have a reason to live? Even if you live who can find you?

So the habit of C++ setting the freed pointer to null should be kept in Java, as this is probably the only way you can free memory.

Final word of advice: Don't use the gc function too often.

And finally why do we need GC

An application's operations on a resource are usually simply divided into the following steps:

1. Allocate memory for the corresponding resource

2. Initialize memory

3. Use resources

4. Clean up resources

5. Free memory

Common ways in which an application manages its resources (memory usage) are 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. Programmer forgets to free memory

2. The application accesses the freed memory

The consequences can be severe, with common memory leaks, scrambled data, and, most of the time, weird and unpredictable behavior, including Access Violation.

The solution given by NET, Java, etc., is to manage memory through the automatic garbage collection mechanism GC. In this way, problem 1 is solved naturally, and problem 2 has no basis of existence.

Summary: can't automatic memory management way so it's easy to produce bug, influence the stability of the system, especially the online server cluster environment, the program appears to perform bug must be positioned to a server and then dump memory analysis bug, extremely discouraged developers, programming, and a steady stream of similar bug disgusting.


Related articles: