. NET heap and stack 04, garbage collection and memory allocation for hosted and unmanaged resources,. net garbage collection

Source: Internet
Author: User

. NET heap and stack 04, garbage collection and memory allocation for hosted and unmanaged resources,. net garbage collection

In ". NET heap and stack 01, basic concepts, value-type memory allocation", I learned the basic concepts of "Heap" and "stack", and value-type memory allocation. We know that when a method is executed, the value type instance allocates memory on the stack, and the reference type instance allocates memory on the heap. When the method execution is complete, instances on the "stack" are automatically released by the operating system, and instances on the "stack" are automatically released.. NET Framework.


In ". NET heap and stack 02, value type and reference type parameter transfer and memory allocation ", we understand the value type parameter and reference type parameter memory allocation during transfer.


In ". NET heap and stack 03, copying and memory allocation of referenced objects", we learned about the memory allocation when copying referenced objects.

 

This article focuses on the garbage collection, processing, and memory allocation of hosted and unmanaged resources.

 

It mainly includes:
■ What types of objects are considered as spam by GC?
■ How to recycle GC?
□Gc recycles objects in the managed heap
□Gc reclaim and process objects in the unmanaged heap
※Resource recycling
○ Collection by destructor
○ Reclaim data through the IDisposable Interface
※Processing static value type variables
※Processing static reference type variables
■ When Will GC be recycled?
■ What operations are performed after GC collection?

 

What types of objects are considered as spam by GC?

When the objects in the managed heap are not referenced by any other objects, these objects will become released spam objects awaiting GC collection.

 

Each application has a set of root pointers, which are not recycled and are maintained by the JIT compiler and CLR runtime. It mainly includes:
● Global/static pointer: pointing to global or local static variables
● Stack pointer: point to the part of the stack space required by the Application Thread
● Register pointer: points to the memory address in the CPU of the managed heap.

 


In the preceding example, if there are five objects in the managed heap, 1 and 5 are referenced by pointers, and 3 is dependent on 1, in this group of managed heap objects, 2 and 4 are recycled and changed to the following:

When a new referenced object is generated during running, it will be placed at the top of this group of objects in the managed heap.

 

How can GC be recycled?

GC recycles objects in the managed heap

GC uses certain algorithms to traverse all objects in the managed heap, and finally forms an reachable object and an inaccessible object. The Inaccessible object will be recycled.

 

Collection and processing of objects in an unmanaged heap by GC

Reclaim Resources

Such as files, database links, and network links. How can these objects in the no-managed heap be recycled?


1. Reclaim through destructor

Public class Sample {// destructor ~ Sample (){}}

 

In the managed heap, instances with destructor will be placed in "Finalization Queue.

 

For those that are not referenced by any other object, if there is no destructor, such as 2, it will be directly recycled. If there is a destructor, such as 4, will be placed in "Freachable Queue", waiting for GC to implement the next round of recycling.


When a destructor is added to a class, additional work is added to the GC, which is expensive. A more practical approach is to enable the class to implement the IDisposable interface.

 

2. Implement the IDisposable interface to reclaim

First, let a class implement the IDisposable interface.

Public class ResourceClass: IDisposable {public void Dispose () {// TODO: Implement reclaim logic }}

 

Call the following in the application to implement recycling.

using(ResourceClass re = new ResourceClass()){    }

 

Processing static value type variables

class Counter{          private static int s_Number = 0;           public static int GetNextNumber()          {                     int newNumber = s_Number;                      // DO SOME STUFF                      newNumber += 1;                     s_Number = newNumber;                     return newNumber;          }}

As shown above, when there is a method to process static fields, you need to note that two threads call GetNextNumber () at the same time will get the same result, and our intention is: every time a method is called, the static field s_Number is increased by 1.

 

We can lock the processing logic block, allowing only one thread to execute at a time.

class Counter{          private static int s_Number = 0;           public static int GetNextNumber()          {                    lock (typeof(Counter))                    {                             int newNumber = s_Number;                              // DO SOME STUFF                              newNumber += 1;                             s_Number = newNumber;                             return newNumber;                    }          }}

 

Processing of static reference type variables

class Olympics{          public static Collection<Runner> TryoutRunners;} class Runner{          private string _fileName;          private FileStream _fStream;           public void GetStats()          {                    FileInfo fInfo = new FileInfo(_fileName);                    _fStream = _fileName.OpenRead();          }}
Above, in the GetStats () method, since FileStream is not closed in time, if Olympus happens to have a collection of 0.1 million Runner, all 0.1 million Runner execute the Gettats () method that does not close FileStream, this will be a disaster!

 

The Singleton mode can effectively avoid the above problems. It ensures that only one instance of a class exists in the memory at any time.

public class Earth{    private static Earth _instance = new Earth();    private Earth(){}    public static Earth GetInstance(){return _instance;}}

Above, the necessary components of the singleton model include:
1. Private Static reference type variable
2. Private Constructor
3. Obtain static methods of class instances

 

When Will GC be recycled?

GC periodically executes garbage collection and memory cleanup. GC is started in the following situations:
● Insufficient hosting heap memory overflow
● Call the GC. Collect () method to forcibly execute garbage collection.
● Windows reports insufficient memory
● CLR uninstall AppDomain

 

What operations are performed after GC collection?

After GC garbage collection, multiple "holes" of collected objects will appear on the managed heap. To avoid Memory fragments of the managed heap, the memory will be re-allocated and the managed heap will be compressed.

 

References:

C # Heap (ing) Vs Stack (ing) in. NET: Part IV

NET (version 2nd), Author: Wang Tao.

 

". NET heap and stack" series include:

. NET heap and stack 01, basic concepts, value type memory allocation. NET heap and stack 02, value type and reference type parameter transfer and memory allocation. NET heap and stack 03, reference type object copy and memory allocation. NET stack and stack 04, garbage collection and memory allocation for hosted and unmanaged Resources
C # hosting and non-hosting problems with C ++

C # Is a memory-hosted object. The new object C # will automatically create a system pointer pointing to it. If all the pointers you have created are destroyed ,. the NET system will automatically use the system pointer to destroy the space. This is the principle of garbage collection. You don't need to worry about the new object after it is used up. Anyway, the system will solve all problems, however, you can also manually destroy objects by calling the Dispose method. Hosting is not related to language rather than usage, it's like if a bad guy has done a good thing, then he is no longer a bad guy?
C ++ is unmanaged. new objects must be manually destroyed. Otherwise, memory leakage occurs. C ++ uses delete to destroy memory. delete is a statement operator rather than a function, you can also overload the delete operator, but delete [] is required to delete the delete array in C ++.

In the Net hosting code, we don't have to worry about memory vulnerabilities.

Because there is a memory recovery mechanism (GC), but this is only limited to those managed resources, for unmanaged resources, it is still necessary to manually release. There are many detailed explanations on why Baidu can search for managed resources.

Related Article

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.