The first article in the first second of the new year at the beginning of the new yearArticle, 7 in the net Discovery series-an in-depth understanding of the. NET garbage collection mechanism (jiebei) and a New Year gift for all park friends!
About. net garbage collector (garbage collection), aicken is already in the ". the net Discovery series contains two articles. This article is a supplement to the previous two articles. net Discovery series "Article index can be found at the end of this article.
Section 1. Garbage CollectionAlgorithmFull GC)
The garbage collector tracks all referenced objects, sorts out objects that are no longer referenced, and recycles the corresponding memory. It uses the "mark and clear" algorithm to recycle objects in two steps:
Step 1. Mark-sweep: slave ApplicationProgramBased on the root of the heap, traverse all the objects dynamically allocated on the heap, specify the objects to be recycled, mark the surviving objects, and mark them.
Step 2. compact: moves the surviving objects in the memory, modifies their pointers, and keeps them in the memory. In this way, idle memory is continuously released, it also solves the memory fragmentation problem. This process can also be used to compress pointers.
The garbage collector generally divides the objects in the managed heap into three generations, which can be called by GC. maxgeneration learns that objects are divided into generations based on the length of time they exist. The shortest score is 0th generations, the longest score is 2nd generations, and the objects in 2nd generations are usually relatively large, the second generation space is called large object heap. For the collection of 2 generation objects, the biggest difference is that there is no compression process for pointer movement.
Figure 1 collection of objects
As shown in, the area on the left is the structure of the first GC. Note that GC marks the surviving objects instead of the objects to be recycled, objects B and D are not marked, so they are recycled. GC then moves the object memory pointer to make the space continuous.
Next, let's take a look at the middle part. The second GC starts, and the C object is not marked, so it is recycled. Then, the three objects A, D, and F are compressed, continuous memory space is formed, and 1st, 2, and 3 generations are formed.
Next, let's look at the rightmost part. The D object is not marked. Because the D object is in the 2nd generation, after the D object is recycled, the GC does not start the compression step, resource costs are high for pointer movement of large objects.
For GC of generation 2nd, it is called full GC, and the newly allocated objects are allocated in the order of addresses in generation 0th (the maximum length of generation 0 space is usually 256 k). They are usually some local variables; the 1st-generation (the maximum length of the 1-generation space is usually 2 MB) is the objects that still reside in the memory after the 0-generation garbage collection. They are usually some objects such as forms and buttons; the 2nd generation is the objects that still reside in the memory after several garbage collections. They are usually some application objects.
It can be seen that a full GC requires the most resources, which may be several or dozens of seconds.
The memory allocation of the managed heap is in segments. When CLR is started, two segments are usually created for GC heap to store 0th, 1 and 2nd objects, respectively, the following figure shows the GC heap information through windbg:
Figure 2 Check GC heap status in windbg
It can be seen that the GC heap is divided into two segments, three generations, with the decimal difference of the starting address of each generation being 12.
In terms of understanding, it should be noted that GC recycles the reference type in the program, and the value type is stored in the stack, when a value-type object is out of the scope, the memory is automatically released-that is, the stack is played, and the garbage collector management is not required.
Section 2. GCWorking Mode
There are three GC working modes: workstation GC with concurrent GC off, workstation GC with concurrent GC on, and server GC, in. in NET 2.0 or later versions, you can modify the config file to change the GC working mode. For example, enable server GC:
< Configuration >
< Runtime >
< Gcserver Enabled = " True " />
</ Runtime >
</ Configuration >
You can also use the. NET Configuration tool to view the node attributes of "My Computer" to conveniently change the GC working mode, for example:
Figure 3 GC Mode
Workstation GC without concurrent:For a single-CPU server, the policy engine adjusts the GC frequency and uses the pending-> Search and Mark-> compression-> recovery process for GC.
Workstation GC with concurrent:Compared with the non-concurrent GC mode, concurrent GC has a more agile response speed. winform applications and Windows Services use this mode by default, and workstation GC can only be used on a single CPU machine, the default value is workstation GC with concurrent.
In this mode, 0th and 1 generation of collection still need to temporarily suspend the application. Only 2nd generation of collection will be processed in parallel. This type of parallel collection uses multiple CPUs.
The full GC process is divided into several transient sub-processes to freeze the thread. The application can still process the full GC process in parallel.
To run normally. This mainly sets a large number of 0th generation space so that when full GC is enabled, CLR can still allocate memory in 0th generation. If full GC is enabled, the 0th generation memory is exhausted, then the application will be suspended, waiting for the completion of full GC.
Server GC: Used for multi-CPU servers. This GC mode has high performance and efficiency. In this mode, CLR creates a dedicated GC thread for each CPU. Each CPU can independently perform GC operations for the corresponding heap. These GC threads work in a non-concurrent manner, collection tasks and threads cannot work normally at the same time, that is to say, 0th, 1, and 2 generations of collection will suspend the application thread.
In. Net 4.0, there is a new garbage collection mechanism called background collection. This mechanism is based on concurrent GC. As mentioned above, in the workstation GC with concurrent mode, CLR can still allocate memory in the zero generation during the full GC process, if the 0-generation memory is used up during full GC, the application will be suspended and the full GC process will be completed.
This process works in the background collection mechanism. During full GC, 0th and 1 generations can be collected at the same time, and the background collection is completed by an independent thread, this process task has a higher priority than 0th and 1 generation collection. If you need to collect 0th and 1 generation tasks in the background, the background collection will wait until 0th and 1 generation are collected.
Of course, 0th and 1-generation collection requires the application to be suspended for a short time.
The back-end collection also dynamically adjusts the capacity of 0th and 1 generation according to the instructions of the policy engine, reducing the number of front-end collection (0th and 1 generation collection) times.
Section 3. Net 4.0Garbage Collector in
In. net 3.5 SP1, the following method is added in the framework and optimized in 4.0, GC. registerforfullgcnotification, GC. waitforfullgcapproach, GC. waitforfullgccomplete, GC. cancelfullgcnotification, these methods are for full GC (complete collection.
1. gc. registerforfullgcnotification:This method returns a signal notification for full GC. This method has two parameters:
IntMaxgenerationthreshold
IntLargeobjectheapthreshold
These two parameters mean the number of surviving objects in the 2nd generation and the number of objects in the object heap. If these two parameters are met, a notification is triggered, from this perspective, LOH may not be the 2nd generation ,.. Net GC may not be just three generations,
In this case. Net Discovery series 3-deep understanding of. Net garbage collection mechanism (I).
2. gc. cancelfullgcnotification:Cancellation of registered spam notifications
Examples of calling these two methods:
Code
// Variable for continual checking in
// While loop in the waitforfullgcproc method.
Static Bool Checkforpolicy = False ;
// Variable for suspending work
// (Such servicing allocated server requests)
// After a notification is received Ed and then
// Resuming allocation after inducing a garbage collection.
Static Bool Ballocate = False ;
// Variable for ending the example.
Static Bool Finalexit = False ;
// Collection for objects that
// Simulate the server request workload.
Static List < Byte [] > Load = New List < Byte [] > ();
Public Static Void Main ( String [] ARGs)
{
Try
{
// Register for a notification.
GC. registerforfullgcnotification ( 10 , 10 );
Console. writeline ( " Registered for GC notification. " );
Checkforpolicy = True ;
Ballocate = True ;
// Start a thread using waitforfullgcproc.
Thread thwaitforfullgc = New Thread ( New Threadstart (waitforfullgcproc ));
Thwaitforfullgc. Start ();
// While the thread is checking for communications in
// Waitforfullgcproc, create objects to simulate a server workload.
Try
{
Int Lastcollcount = 0 ;
Int Newcollcount = 0 ;
While ( True )
{
If (Ballocate)
{
Load. Add ( New Byte [ 1000 ]);
Newcollcount = GC. collectioncount ( 2 );
If (Newcollcount ! = Lastcollcount)
{
// Show collection count when it increases:
Console. writeline ( " Gen 2 Collection count: {0} " , GC. collectioncount ( 2 ). Tostring ());
Lastcollcount = Newcollcount;
}
// For ending the example (arbitrary ).
If (Newcollcount = 500 )
{
Finalexit = True ;
Checkforpolicy = False ;
Break ;
}
}
}
}
Catch (Outofmemoryexception)
{
Console. writeline ( " Out of memory. " );
}
Finalexit = True ;
Checkforpolicy = False ;
GC. cancelfullgcnotification ();
}
Catch (Invalidoperationexception invalidop)
{
Console. writeline ( " GC configurications are not supported while concurrent GC is enabled. \ n "
+ Invalidop. Message );
}
}
3. gc. waitforfullgcapproach:This method returns the gcnotificationstatus enumeration value to obtain whether the Garbage Collector will start the complete garbage collection. When the enumeration is succeeded,
You should do some work, such as preventing Manual calls to the GC. Collect () method to avoid wasting resources.
This method should beGC. waitforfullgccomplete ()Also used to determine that the CLR executes the complete garbage collection.
Code
// Check whether full collection will be started
Gcnotificationstatus s = GC. waitforfullgcapproach ();
If (S = Gcnotificationstatus. succeeded)
{
// Do not GC. Collect ()
}
Else If (S = Gcnotificationstatus. canceled)
{
// GC. Collect ()
}
4. gc. waitforfullgccomplete:
To obtain whether the Garbage Collector has completed the complete garbage collection:
Code
Gcnotificationstatus s = GC. waitforfullgcapproach ();
S = GC. waitforfullgccomplete ();
If (S = Gcnotificationstatus. succeeded) // Full GC has been completed
{
// Do not GC. Collect ()
}
Else If (S = Gcnotificationstatus. canceled)
{
// GC. Collect ()
}
I amAicken)Please keep an eye on my next article.
". Net Discovery series" is recommended:
. Net Discovery series 5-Me JIT (I)
. Net Discovery series 6-Me JIT (lower)
. Net Discovery series 3-deep understanding of. Net garbage collection mechanism (I)
. Net Discovery series 4-deep understanding of. Net garbage collection mechanism (II)
One of the. NET Discovery series-string from entry to mastery (on)
. Net Discovery series II-string from entry to mastery (lower)