(Reference) memory reclaim mechanism in. net

Source: Internet
Author: User
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 as Visual Basic, 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 programmer forgets to release the memory after using the memory, it will 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 is 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 that 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 put objects of the same type 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 these objects are placed in adjacent areas of the managed heap, 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. In this 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 object pointed to by the register ), 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. After the Garbage Collector checks all objects, there is a list of objects directly or indirectly referenced by the root object and the root object, other objects that are 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 the object is recycled, the garbage collector checks the end list to see if the finalize () method of the object needs to be called. If yes, the garbage collector adds the pointer to the object to a worker queue, which 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, so that the Garbage Collector knows that the terminated object can be cleared during the next object collection. From the above we can see that a major 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 it will 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 defining objects according to the following pattern when implementing classes with fianlize () methods:

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 generational garbage collector ). The lifetime Garbage Collector divides the memory into many managed heaps, each of which corresponds to a lifetime level. The 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 will change the size of the managed heap if it finds that changing the size can improve the performance. For example, when the application initializes many small objects and these objects are quickly recycled, the garbage collector will change the 0-level managed heap to 128 K and increase the recycling 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.

Before the application is initialized, all levels of managed stacks are empty. When an object is initialized, it is put into a managed heap with a level of 0 in the initialization sequence. The storage of objects in the managed heap is continuous, which makes the managed heap fast to access objects, because the managed object does not need to search for 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 containing 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 check whether any objects can be recycled. 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, move the pointer of the 0-level managed heap 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 to a Level 2 hosting 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 managed heaps of all levels. In most cases, developers do not need to interfere with the action of the garbage collector, but in some cases, for example, when the program performs very complex operations and wants to confirm that the garbage objects in the memory have been recycled, you can use the above method. Another method is 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 a program has a string attribute, which occupies a certain amount of 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 determines that an object is no longer used, the developer must also make sure that no other object references the object. Otherwise, the garbage collector will not recycle the object.

It is also worth mentioning that the finalize () method should be completed in a short period of time, because the Garbage Collector limits a time for the finalize () method, if finalize () if the method has not been completed within the specified time, the garbage collector terminates 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.