How to Understand the garbage collection mechanism in. net

Source: Internet
Author: User

The. NET Framework Garbage Collector manages the memory allocation and release of applications. Every time you use new
When the operator creates an object, the runtime database allocates memory for the object from the managed heap. As long as the address space in the managed heap is available, the runtime will continue to allocate space for new objects. However, the memory is not infinitely large. Eventually
The recycle collector must be executed to release some memory. The garbage collector Optimization engine determines the best time to recycle based on the ongoing allocation. When the Garbage Collector executes collection, it checks that the managed heap is no longer
The objects used by the application and perform necessary operations to reclaim the memory they occupy.

Deep understanding of. Net memory recovery mechanism

[Preface:] the. NET platform provides many new functions that can help programmers produce more efficient and stable code. One of them is the garbage collector (GC ). This article will explore this function in depth to learn how it works and how to write code to better use the features provided by this. NET platform.

Memory recovery mechanism in. net

 
The garbage collector is used to manage the memory allocation and release of applications. Before the appearance of the garbage collector, the programmer needs to apply for memory space from the system when using the memory. Some languages, such
Visual Basic, which can automatically apply for memory space from the system. However, in languages such as Visual C ++, programmers are required to apply for memory space in program code. If
The sequencer forgets to release the memory after using the memory, which may cause memory leakage. But with the garbage collector, programmers do not have to worry about whether the objects in the memory are released after they leave the lifetime. When an application
When running, the garbage collector sets a managed heap. The managed heap is similar to the heap in C language, but the programmer does not need to release objects from the managed heap, and the storage of objects in the managed heap is continuous.

 
Every time a developer creates an object using the new operator, the runtime allocates memory for the object from the managed heap. The newly created object is placed after the last created object. The garbage collector saves a pointer
The pointer always points to the memory space after the last object in the managed heap. When a new object is generated, the runtime knows where the new object should be stored in the memory. At the same time, developers should
Objects are put together. For example, when developers want to write data to the database, they need to create a connection object, a command object, and a DataSet object. If
Some objects are placed in the adjacent area of the hosting heap, and they can be accessed very quickly.

When the pointer of the garbage collector points to the memory space outside the managed heap, the garbage in the memory needs to be recycled. Here
In the process, the garbage collector first assumes that all objects in the managed heap need to be recycled. Then it looks for the object referenced by the root object in the managed heap (the root object is a global, static, or active local variable)
And the objects pointed to by the register), locate them, add them to the list of valid objects, and search for objects that have been searched for to see if any objects have been referenced by new valid objects. Until the Garbage Collector has checked the site
Some objects have a list of objects directly or indirectly referenced by the root object and the root object, while other objects not in the table are recycled from the memory.

When an object is added to the managed heap
If it implements the finalize () method, the garbage collector adds a pointer to the object in its finalization list. When this object
When the object is recycled, the garbage collector checks the final list to check whether the finalize () method of the object needs to be called. If yes, the garbage collector adds a pointer to the object to a worker queue,
The worker queue stores the objects that are going to call the finalize () method. Objects in this step are not really spam objects. Therefore, the garbage collector has not recycled them from the managed heap.

 
When the object is ready to be terminated, another Garbage Collector thread will call the finalize () method for each object in the worker queue. After the call is complete, the thread removes the pointer from the worker queue.
The garbage collector knows that the object to be terminated can be cleared during the next collection. From the above, we can see that a large part of the additional work brought about by the garbage collection mechanism is to call the finalize () method,
Therefore, in actual programming, developers should avoid implementing the finalize () method in the class.

Another problem with the finalize () method is that developers do not know
When will it be called. Unlike the destructor in C ++, it is called when an object is deleted. To solve this problem, an interface idisposable is provided in. net. Microsoft recommends
Define the object according to the following pattern when implementing a class with the fianlize () method:

Public class class1: idisposable
{
Public class1 ()
{
}

~ Class1 ()
{
// The Garbage Collector calls this method, so the parameter must be false.
Dispose (false );
}

// This method is defined in the idisposable interface.
Public void dispose ()
{
// This method is called by a program. After this method is called, the object is terminated.
// Because we do not want the Garbage Collector to terminate the object again, we need to remove the object from the end list.
GC. suppressfinalize (this );
// Because the program calls this method, the parameter is true.
Dispose (true );
}

// This method is used to complete all the work related to recycling.
Private void dispose (bool disposing)
{
Lock (this) // avoid thread errors.
{
If (disposing)
{
// The programmer needs to release the resources occupied by the object.
}

// The object will be terminated by the garbage collector. Add other Code related to object clearing.
}
}
}
 
 
Now we understand the basic principles of the garbage collector. Next let's take a look at how the garbage collector works internally. There are many types of garbage collectors. Microsoft implements a life-time Spam
Generational garbage collector ). The lifetime Garbage Collector divides the memory into many managed heaps, each of which corresponds to a lifetime level. Raw
The deposit Garbage Collector follows the following principles:

The shorter the lifetime of a newly generated object. The longer the object is generated, the longer the lifetime of the object. For the Garbage Collector, it is always faster to recycle some objects than to recycle all objects. Therefore, the garbage collector recycles objects that have a short life cycle more frequently than those that have a long life cycle.

 
The. NET Garbage Collector currently has three lifetime levels: 0, 1 and 2. The initial size of the managed heap corresponding to levels 0, 1, and 2 is 256 K, 2 m, and 10 m respectively. The garbage collector is discovering
Changing the size will increase the performance of the managed heap. For example, when the application initializes many small objects and these objects are quickly recycled, the garbage collector will change the 0-level hosting heap
128 K, and increase the recovery frequency. If the opposite is true, the garbage collector will increase the size of the managed heap when it finds that a large amount of space cannot be recycled in a 0-level managed heap.
Initialize the application
Before, all levels of managed stacks were empty. When an object is initialized, it is put into a managed heap with a level of 0 in the initialization sequence. Objects are stored continuously in the managed heap.
It is faster to host the heap access object, because the hosting object does not have to search the memory. The garbage collector saves a pointer to the memory space after the last object in the managed heap. Figure 1 shows
A zero-level managed heap for four objects.

Figure 1 hosting heap containing four objects

 
When the 0-level managed heap is filled with objects, for example, when a program initializes a new object, the size of the 0-level managed heap exceeds 256 kb, the garbage collector checks all objects in the managed heap to see if any objects are available.
To recycle. When the recycle operation starts, as mentioned above, the garbage collector will find the objects directly or indirectly referenced by the root node and the root node, and then transfer these objects to the level 1 managed heap, and manage the 0-level hosting
The heap pointer moves to the initial position to clear all objects. Meanwhile, the garbage collector compresses the level 1 managed heap to ensure that there is no memory gap between all objects. When Level 1 hosting is full, the object will be transferred
2-level managed heap.

For example, in figure 1, the garbage collector starts to recycle objects, assuming that D Objects will be recycled, and the program creates e and f objects. In this case, object 2 in the managed heap is shown.


Figure 2 0-level and 1-level managed heaps after recycling objects

Then the program creates new objects G and H, and triggers the Garbage Collector again. Object E will be recycled. In this case, object 3 in the managed heap is shown.


The principle of the Garbage Collector for survival is also exceptional. When the object size exceeds K, the object will be placed in the "large object area ". Objects in the large object area will not be recycled or compressed by the garbage collector. This is to force the Garbage Collector to only recycle small objects to improve program performance.

Control the Garbage Collector

 
The. NET Framework provides many methods for developers to directly control the behavior of the garbage collector. By using GC. Collect () or
GC. Collect (INT generationnumber) developers can force the Garbage Collector to recycle all levels of managed heaps. Developers in most cases
The user does not need to interfere with the action of the garbage collector, but in some cases, for example, when the program performs a very complex operation and wants to confirm that the garbage objects in the memory have been recycled, you can use the above method. Another Party
Method: GC. waitforpendingfinalizers (). It can suspend the current thread until the thread in the processor queue clears the queue.

  
The best way to use the garbage collector is to track the objects defined in the program and manually release them when the program does not need them. For example, an object in the program has a string attribute, which occupies a certain amount
Memory space. When this attribute is no longer used, developers can set it to null in the program, so that the garbage collector can recycle the space occupied by this string. In addition, if the developer decides not to enable
When using an object, make sure that no other object references the object at the same time. Otherwise, the garbage collector will not recycle the object.

It is also worth mentioning that the finalize () method should
In a short period of time, this is because the Garbage Collector limits a time for the finalize () method. If the finalize () method has not been completed within the specified time, the garbage collector will
Terminate the thread that runs the finalize () method. In the following cases, the program calls the finalize () method of the object:

The level 0 garbage collector is full.

The program calls the garbage collection method.

The Common Language Runtime is detaching an application domain.

The public Language Runtime is being uninstalled.

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.