(rpm). NET platform garbage collection mechanism

Source: Internet
Author: User

Introduction: using C + + for programming, memory processing is absolutely the most headache for every programmer. But for The. NET platform using the C # language development system, Memory management can be said to be no longer a problem. Under The. net platform, the CLR is responsible for managing memory, and the garbage collector in the CLR Gc:garbage Collection is responsible for performing the cleanup of the memory, but the GC is only responsible for cleaning up the garbage objects on the managed heap, and for unmanaged resource objects, The GC does not Work. Must be cleaned manually by the program Developer. Here's a little explanation: in general, unmanaged resources mainly include database links, file handles, com objects, sockets, GDI + objects, mutexes, and so On.

Before introducing gc, it is necessary to briefly describe the CLR management memory areas in. net:

1. Stack: used to assign an instance of a value type. The stack is managed by the primary operating system, and is not controlled by the garbage collector, and its storage units are automatically freed when the method at which the value type instance resides ends. Stack execution is efficient, but storage capacity is Limited.

2. GC heap: used to allocate small object Instances. If the size of the reference type object instance is less than 85000 bytes, The instance is configured on the GC heap, and the garbage collector may compress the GC heap when there is memory allocation or recycling.

3. Loh:large Object heap, which is used to allocate large object Instances. If an instance of a reference type object is not less than 85000 bytes in size, the instance is assigned to the Loh heap, and the Loh heap is not compressed and is only reclaimed when full GC is Reclaimed.

  

Since to clean up the rubbish, then must understand what is rubbish, garbage understanding: an object becomes "garbage" means that the object is not referenced by any other object. therefore, The GC must traverse all objects in the managed heap using a certain algorithm, eventually forming an object graph, and unreachable objects will be disposed of as garbage objects for Collection.

After knowing what is rubbish, it is sure to question how GC recycles garbage. under The. net platform, each application has a set of roots (pointers) that point to the storage location in the managed heap, maintained by the JIT compiler and the CLR runtime, a list of root pointers, mainly including global variables, static variables, Local variables, register pointers, and so On. it is through the root pointer list that the GC obtains the object graph in the managed heap, which defines the objects in the managed heap referenced by the application root, and when the GC starts, it assumes that all objects are recyclable garbage, begins to traverse all the roots, and marks the object of the root reference as an object to be added to the object Graph. During traversal, if the object referenced by the root also references other objects, the object is also added to the object graph, and so on, theGC passes through the root list recursively, it will be able to find all the objects that can be reached and form an object Graph. While those unreachable objects are considered recyclable objects, theGC then runs the garbage collection process to free up the garbage Object's memory space. This collection algorithm is called: tag and purge collection Algorithms.

Garbage collection generally occurs under the following conditions:

1 when an out-of-memory overflow occurs, it is more accurate to say that the 0-generation object is Full.

2 Call the GC. The Collect method enforces garbage Collection. (generally do not perform this METHOD)

3 when Windows reports low memory, theCLR enforces garbage Collection.

4 when the CLR unloads the appdomain, theGC performs garbage collection on all age-old objects.

5 other situations, such as insufficient physical memory, exceeding the memory segment threshold for short-lived generations, the running host refuses to allocate memory, and so On.

Garbage collection Operation Mechanism:

The garbage collector divides the objects in the managed heap into three generations: 0, 1, and 2, and when the CLR initializes, it chooses to set a different threshold capacity for three generations, typically: the No. 0 generation is about 256KB, 1th generation 2MB, 2nd generation 10MB. The larger the capacity, the less efficient the GC collector automatically adjusts its threshold capacity to improve execution efficiency. After CLR initialization, objects that were first added to the managed heap are positioned as No. 0-generation objects, and when garbage collection is performed, Delling objects that are not reclaimed will be promoted to a 1th-generation object, and the new object is still not a No. 0-generation object. The smaller the Delling, the more new the object, usually with the shortest life cycle, so the GC always collects the No. 0 generation of unreachable object memory First.

As objects continue to be created, garbage collection starts by checking only 0-generation objects and reclaiming 0-generation garbage objects. The 1-generation object, because it does not reach the 1-generation capacity threshold, does not carry out garbage collection operation, which effectively improves the efficiency of garbage collecting, and this is also the performance optimization function of the aging mechanism in garbage recovery. When a No. 0-generation object frees up enough memory to create a new object, and the 1-generation Object's volume exceeds the capacity threshold, the garbage collector will garbage-recycle both 0-generation and 1-generation Objects. After recycling, the 1-generation object that was not recycled changed the 2-level object, the 0-generation object that was not reclaimed was promoted to a 1-generation object, and the new object was still a No. 0-generation object.

Note: Microsoft strongly recommends that you do not enforce garbage collection through the Gc.collect method, which interferes with the way the GC itself works, and collect the object by increasing its age and disrupting the memory usage of the Application. Consider using the Gc.collect method to invoke the collector only if you explicitly know that a large number of objects are stopping the Reference.

The above describes some of the mechanisms involved in Garbage manager GC cleanup of managed resources, however, for unmanaged resources, developers need to manually clean up, mainly By: Finalize method and Dispose Method.

Finalize:

The Finalize method is also known as a terminating operation: releasing an unmanaged resource by implementing a Finalize method on the custom type , and terminating the resource by calling the Finalize method before the Object's memory is reclaimed . Overrides the Finalize method in the destructor, and when the garbage manager starts, the GC automatically executes its Finalize method to clean up unmanaged resources for garbage objects that are determined to be recyclable.

protected override void Finalize ()        {            try            {                 //execute custom Resource cleanup operation            }            finally            {                base. Finalize ();            }        }

The disadvantages of Finalize are:

The time to terminate the operation is uncontrollable and the order of execution is not guaranteed.

The Finalize method can greatly damage performance, and the GC uses an internal structure that terminates the session queue to track objects with a finalize method.

Overriding the type object of the Finalize method, the Delling of its reference type object will be promoted, resulting in memory pressure.

Dispose:

The implementation of the dispose pattern is that the defined type must implement the System.IDisposable interface, which defines a public parameterless Dispose method that the programmer can implement to clean up unmanaged resources in the Dispose Method.

An example of using the Dispose method is written in a project below, which frees up resources after the socket has been used

public class socketconnection:idisposable    {        ///logical operation//        ...        .... ..... Implement the Dispose public        void dispose ()        {            try {this                . Clientsock.shutdown (socketshutdown.both);                This. Clientsock.close ();                This. Server = null;            }            Catch (Exception Ex)            {}        }    }

Summarize:

In. net, the resources allocated on the stack are automatically freed after the call ENDS.

The resources in the managed heap are cleaned by the Clr's garbage manager.

For unmanaged resources, It must be done by the program designer, and for Finalize and dispose, it is best to use the Dispose Method.

(rpm). NET platform garbage collection mechanism

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.