How the. NET GC garbage collection mechanism works

Source: Internet
Author: User

First look at the managed resources--. NET refers to the host is only for memory this piece, not for all resources; for stream, database connection, COM object, GDI + related objects, etc., these objects are not managed by. NET as unmanaged resources, and for memory recycling and management, is done by the GC, while the other resources need to be released manually.

Second, the definition of rubbish--. NET types fall into two categories, one is a value type and the other is a reference type. The former is allocated on the stack and does not require GC reclamation; the latter is allocated on the heap, so its memory release and recycling needs to be done by GC. GC is all called "garbage Collector", as the name implies is the garbage collector, then only the object called garbage can be recycled by GC. That is, the memory used by a reference type object needs to be reclaimed by GC and needs to be garbage first. Then. net How to determine a reference type object is garbage,. NET judgment is simple, as long as it is determined that this object or its contained sub-object does not have any reference is valid, then the system thinks it is garbage.

With these two basic concepts in view, let's talk about how GC works and how it functions. The release and recycling of memory needs to accompany the program's operation, so the system arranges separate threads for the GC. The GC's work is, in general, querying whether objects in memory become garbage, and then releasing and recycling the garbage. Then the GC takes a certain priority algorithm for memory recycling to recycle memory resources. Second, there are two kinds of garbage in memory, one is to call the destructor of the object, and the other is not to call. GC for the former recycling needs to be done in two steps, the first step is to call the object's destructor, the second step is to reclaim memory, but note that these two steps are not in the GC round-robin completion, that is, the need to round two times, in contrast to the latter, Only the memory is recycled.

Garbage collection algorithm-generational (Generation) algorithm

Generation is a mechanism used by the CLR garbage collector, and its sole purpose is to improve the performance of the application. Recycling is faster than recycling the entire heap.

CLR managed heap support 3 generation: No. 0 generation, 1th generation, 2nd generation. The No. 0 generation of space is about 256KB, the 1th generation is about 2M, and the 2nd generation is about 10M. The newly constructed object is assigned to the No. 0 generation.

As shown, when the No. 0 generation of space is full, the garbage collector starts recycling, the unreachable object (C, E) is recycled, and the surviving object is classified as the 1th generation.

When the No. 0 generation of space is full, and the 1th generation is beginning to have a lot of unreachable objects and the space will be full, then both generations of garbage will be recycled. The surviving object (to reach the object), the No. 0 generation to the 1th generation, the 1th generation to the 2nd generation.

The actual CLR's generation-recycling mechanism is more "intelligent", and if the newly created object has a short life cycle, the No. 0 generation of garbage will be reclaimed by the garbage collector immediately (no more space allocated). In addition, if you recycle the No. 0 generation, and find that there are many objects "up to", and do not release much memory, will increase the No. 0 generation of the budget to 512KB, the recovery effect will be changed to: The number of garbage collection will be reduced, but each time will be recycled a lot of memory. If much memory has not been freed, the garbage collector will perform a full recycle (3 generation) and, if not enough, will throw a "memory overflow" exception.

In other words, the garbage collector dynamically adjusts the allocated space budget for each generation based on the size of the reclaimed memory! Achieve automatic optimization!

Summarize

. NET garbage collector basically works by clearing the unreachable object by the most basic principle of Mark clearing, compressing and defragmenting the available memory like disk defragmentation, and finally realizing the performance optimization by the generational algorithm.

After the previous introduction, you can know that the destructor can only be called by the GC, it is not possible to determine when it is called, so it is not reasonable to use it as a resource release, because the resource is not released in time, but in order to prevent the resource leakage, after all, it will be called by the GC, so the destructor can be used as a The difference between the two methods of close and dispose is that it is possible for this object to be reused after the Close method of the object has been called, whereas the Dispose method requires that the resource for this object be marked as useless, that is, the object is destroyed and can no longer be used. For example, the common SqlConnection class, when the Close method is called, can reopen the database connection through open, and when the object is completely unused, you can call the Dispose method to flag the object as useless and wait for GC to recycle. Once you understand the meaning of these two methods, you should not distort the meanings of the interfaces you add to your class.

----------------------------------The following is a summary of a master on Csdn----------------------------------------------

1. The Finalize method (in C # is a destructor, the following destructor) is used to dispose of unmanaged resources, and managed resources are automatically reclaimed by the GC. So, we can also differentiate between managed and unmanaged resources. All of the resources that will be automatically reclaimed by GC are managed resources, and resources that cannot be automatically reclaimed by GC are unmanaged resources. The use of unmanaged resources directly in our classes is rare, so we do not have to write destructors basically.
2, most of the unmanaged resources will have a lot of negative impact on the system, such as the database connection is not released may cause the connection pool to run out of available database connections. A file that does not close causes other processes to not read and write to the file.

Implementation model:
1. Because most unmanaged resources require manual release, we should expose a method specifically for releasing unmanaged resources. The Dispose method that implements the IDispose interface is the best model because C # supports the using statement fast and can automatically call the Dispose method when it leaves the statement block.
2, although you can manually release unmanaged resources, we still want to release the unmanaged resources in the destructor, so that is a secure application. Otherwise, if you forget to manually release unmanaged resources because of a programmer's negligence, it can have disastrous consequences. So releasing an unmanaged resource in a destructor is a remedial measure, at least for most classes.
3, because the invocation of destructors will cause the GC to reduce the efficiency of object recycling, so if you have done what the destructor is doing (for example, releasing unmanaged resources), you should use the SuppressFinalize method to tell the GC not to need to execute an object's destructor.
4. Destructors can only release unmanaged resources and cannot operate on any managed objects/resources. Because you can't predict the timing of the destructor, you might have freed the managed resources you were working on when the destructor was executed. This will result in serious consequences.
5. (This is a rule) if a class has a member that implements the IDispose interface type and creates (note that it is created, not received, it must be created by the class itself) its instance object, then this class should also implement the IDispose interface, And in the Dispose method, all the dispose methods that implement the members of the IDispose interface are called.
This is the only way to ensure that all objects that implement the IDispose interface's object's Dispose method can be called to ensure that any resources that need to be freed can be released manually.

How the

. NET GC garbage collection works (go)

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.