ArticleDirectory
- Reference count
- Tracking collector
- Collection by generation
Role of garbage collection
Obviously, you will answer to release the memory by clearing unnecessary objects, but don't forget that another important role of garbage collection is to eliminate the fragments of heap memory space.
Garbage collection policy reference count
This is an early strategy. It is very simple. If object A is referenced, its count acount is added with 1. If the reference to object A is invalid, acount is reduced by 1. When acount = 0, a. When garbage collection is performed on a, the Count of other objects referenced in a is reduced by 1, so the collection of a may cause a chain reaction.
Advantages: simple and fast
Disadvantage: Circular references cannot be detected. For example, if subclass A of A references a and a references a, a and a will never be recycled. This disadvantage is fatal, so this policy is no longer needed.
Tracking collector
It is also known as the "mark and clear" policy. The basic idea is to traverse the entire object graph from the root object, and mark the referenced object. After the traversal, no marked object can be cleared. The record marking policy can be recorded in the object itself or through bitmap.
My question: will it cause "mistaken killing? After marking, clear an object that has not been marked and suddenly referenced. What should I do?
This problem should not occur because only the current object graph range is used when the object is cleared. An object will expand the object graph from being referenced to being referenced, this is not within the scope of this purge.
The tracking collector usually uses two policies:
1. compression COLLECTOR: if an object is found to be valid during traversal, the object will immediately slide over the idle area to one end of the heap, so that a large continuous idle area will appear on the other end of the heap, this eliminates heap fragments.
2. Copy COLLECTOR: the heap is divided into two areas of equal size, and only one area is used at any time. Objects are allocated in the same region until the region is exhausted. At this time,ProgramThe execution is aborted, the heap is traversed, and objects marked as active are copied to another region. This method is called "Stop and copy ".
The main disadvantage of this approach is: It is too rough to copy all the copies, the granularity is too large, and the overall performance is not high. Therefore, we have a more advanced "collection by generation" collector"
Collection by generation
Based on two facts:
1) Most objects created by most programs have a short life cycle.
2) Most programs create objects with very long lifecycles.
Therefore, the generation-based collection policy is based on the "Stop and copy" policy, which divides objects into class objects based on their lifecycles. It divides the heap into multiple sub-heaps, and each sub-heap serves as a "substitute" object. The youngest generation had the most frequent garbage collection. Without a garbage collection, the surviving objects will "grow" to the older "Generation". The older the "Generation" objects, the fewer the number of them, and the more stable they are, therefore, we can take a very economic strategy to deal with them, simply "take care of" them. In this way, the overall garbage collection efficiency is higher than the simple and crude "Stop and copy.
Train
Algorithm
Before talking about train algorithms, we should first talk about "progressive Collection", which is more efficient than "stopping and copying, however, the range of objects processed by generation collection is still the whole "heap". In some cases, the slow system response caused by the garbage collection overhead still makes the user unable to bear the problem, therefore, we proposed "gradual collection" and adopted the method of small steps to quickly process only a portion of the data in the "Heap" space at a time to complete garbage collection.
Next, let's talk about the train algorithm. First, let's clarify the question: what problems should the train algorithm solve?
Is the train algorithm used to replace the generation-by-generation collection policy? No, it can be said that the train algorithm is a powerful supplement to the generation-by-generation collection policy. We know that the collection by generation policy divides the heap into multiple "generations". The maximum size can be specified for each generation, except for the "mature object space, "mature object space" Cannot specify the maximum size, because it is the "Oldest" object and ultimately the only destination. In addition, these "old guys" have nowhere to go. However, you cannot determine how many old objects a system will eventually squeeze into the "mature object space".
The train algorithm details the organization of the mature object space of the garbage collector collected by generation. The purpose of the train algorithm is to provide time-limited progressive collection in the mature object space.
The train algorithm divides the mature object space into memory blocks of a fixed length, and each time the algorithm is executed separately in a block. Why is it "train algorithm"? This is related to the way algorithms organize these blocks.
Each piece of data is equivalent to a carriage
Each data block belongs to a set, and all data blocks in the set have been sorted. Therefore, a set is like a train.
The mature object space contains multiple sets, so it is like having multiple trains, and the mature object space is like a railway station.
Garbage collection-train algorithm-mature object Area Memory organization form
The fundamental idea of train algorithms is still "divide and conquer". The goal is to achieve gradual recovery and detailed algorithm details. I will describe it in detail next time.
==============================================
The general execution process of the train algorithm is as follows:
1) First, check the entire train with the smallest serial number. If no reference (out of & within the mature object area) is referenced to any objects in the train, the memory of the entire train is recycled directly;
2) If the check result of 1) is false, focus on the carriage with the smallest serial number of the train with the smallest serial number. If the objects of the whole carriage are no longer referenced, recycle them directly;
3) if the objects in the carriage with the smallest serial number are referenced, the objects are transferred. If a carriage from another train is referenced, the current object is transferred to the carriage that references it. If the space of the carriage is insufficient, a new carriage is added, and store the transferred objects in the new carriage. If the reference comes from outside the mature object space, the object is transferred to another train. If you reference another carriage from the current train, the object is transferred to the carriage at the end of the train.
4) after 3) object transfer, the remaining objects can be recycled.
Through the above description, we will notice that the train algorithm needs to scan the target object during garbage collection to ensure that no object reference points to them, which is time-consuming, therefore, the train algorithm uses a memory set to record all external references to a carriage or a train. If the memory set is found to be empty, it indicates that no reference is provided and the carriage or train can be recycled directly.
Finalize method
Purpose: A hook method. Before JVM executes garbage collection on the current object, it can call the Finalize method for some additional work. Note: The Finalize method is called by JVM.
In addition, it should be clear that the Finalize method will increase the complexity of garbage collection. The general process is as follows:
1) The Garbage Collector uses some algorithms to identify all objects that are not referenced and prepares to recycle them (this process is called "first scan ");
2) at this time, the garbage collector must judge whether the object to be recycled has the Finalize method. If so, call it.
3) after all the finalize methods are executed, the garbage collector must perform another scan (called the second scan) to determine whether the objects to be recycled should be recycled, because the Finalize method may "Restore" some objects, this scan is necessary.
There is another thing to remember about finalize: an object's finalize can only be run once (if provided ). This is because the JVM will remember whether the Finalize method of an object has been executed. If it has been executed, but the object is still valid (for example, the Finalize method "revived" itself ), when the object becomes invalid again, the JVM will no longer execute its Finalize method when it recycles the object, and the JVM will treat it as an object that does not provide the Finalize method. Otherwise, the object will never be recycled.
Object touchability Lifecycle
In the view of the garbage collector, each object in the heap has six states:
Strong touchability, weak touchability, soft touchability, shadow touchability, resurrection, and untouchability.
The direct difference between a strong target and a weak form (weak, soft, and shadow) is that the target cannot be referenced by the former is garbage collection, the latter is allowed.
Retriable: although it cannot be touched from the root node's object graph, it is possible to be touched when the Garbage Collector executes some termination methods.
Untouchable: no other object has been referenced.
What is the use of so many States?
To put it simply, soft references allow you to create a cache in the memory, which is related to the overall memory requirements of the program. Weak references allow you to create standard mappings, such as hash tables. The keywords and values of a hash table can be cleared from mappings when no reference is provided to other program components. The Shadow application allows you to implement more complex finalize policies than the Finalize method.
Soft references are easy to understand. Here it is hard to understand weak references. In fact, you only need to give a specific example to understand:
We often use a Map <xxbean, yybean> with the same lifecycle as the entire application to hold some metadata as the cache. If we use hashmap <xxbean, yybean> (strong reference), the lifecycle of all key-values in the map is as long as that of the map, because this is a strong reference. This laid the groundwork for Memory leakage. For example, a key: xxbean is no longer used, but its map is always referenced, as a result, this xxbean will not be recycled. If we use weakhashmap instead of hashmap, this problem can be solved. Once the garbage collector finds that in addition to weakhashmap, it also holds references to xxbean, it will not hesitate to release the key-Value Pair xxbean-yybean.
Last, let's talk about soft references, weak references, and shadow references: Because the garbage collector can decide their own fate, therefore, Java provides a reference queue for developers to monitor the processing of these objects by the garbage collector.
The following APIs must be known:
Java. Lang. Ref. Reference
An example of weak references: http://www.ibm.com/developerworks/cn/java/j-jtp11225/