. Net useless unit recycling

Source: Internet
Author: User

We usually writeProgramRarely write resource management on your own, unless you write a very large application or a large company's own SDK. PGP seenSource codeYou must know that the pgp sdk implements its own memory management. There are a lot of troubles when you manage your memory. If you forget to release the memory, the bugs that have been released and accessed again emerge one after another, which is very difficult to find. Common logic bugs can be found in simple tests without running the program as expected. However, memory problems are hard to be found. In the past, many companies have made great efforts to solve this problem, such as compuware's boundschecker and rational's purify. These tools are also very difficult to use, and the point you often find is the development library you use.Code. Currently,. NET provides a full set of resource management (useless Resource Recycling: garbage collection, or GC for short), which can free us from this and focus on the business problems we should solve. Of course, it is not omnipotent. We 'd better understand its principles so that we can enjoy it better.

The system resources are not infinite. When the memory is used up, the resources are released, and files and network connections are all system resources. In an object-oriented system, everything is an object. Therefore, you must allocate memory from the system to use any resource and release it. There are no more than five steps to use resources:

1. allocate memory for the resource type;

2. initialize the resource status and request non-memory system resources (such as opening files and establishing network connections );

3. access resources through access-type instances (objects), their member variables, methods, etc. (may be multiple times)

4. Clear the resource status and release system resources (such as closing files and closing network connections );

5. release memory

The memory problems we encountered are generally solved in the above five steps. The useless unit recovery (GC) mechanism provided by. Net can basically solve these problems. However, GC does not know how to clear the resource status and release system resources (that is, the fourth step above), so we need to use Fina

CLR implements a managed heap, which requires that all resources be allocated from the heap and do not need to be released. The following describes in detail how objects are allocated in the heap and how garbage collection is useless.

During process initialization, CLR retains a piece of continuous memory, which is the managed heap. CLR also maintains a pointer for the managed heap. This pointer always points to the next allocable memory space, which is called nextobjptr.

When the program applies to new to create an object, new first checks whether there is sufficient memory space in the heap. If yes, it allocates space for the object and calls the object constructor, return the address of the allocated space. Next, nextobjptr points to the address of the remaining space, that is, the next address that can be allocated. For example:

The dotted line in the figure is the starting address of nextobjptr. After successfully allocating Object C and returning the address, nextobjptr moves to the position of the solid line.

Again
Let's take a look at the heap memory allocation methods of common applications. The normal memory allocation mode maintains a list of idle memory. The system first traverses the list of idle space, finds a sufficient space, and splits it out.
Allocate enough space, and then add the remaining space to the free space list. In history, there have been many implementations of process heap memory allocation.AlgorithmSuch as the well-known binary classification. However, the memory allocation method of. NET is much faster.

But the memory is not infinite. What should I do if the heap space is allocated to light? When the CLR allocates memory, it starts useless space recovery if it finds that the idle space in the heap is insufficient. GC releases the memory occupied by objects in the heap that are no longer used, and sorts the heap so that the remaining continuous space is to be allocated, of course, if there are no objects to be released or the memory is insufficient after the release, an outofmemoryexception will be thrown. How does GC determine that an object is no longer used?

Each application has a set of roots that contain the storage units of a group of objects in the managed heap. Objects considered root include:

1. All global and static objects;

2. Parameters of local objects and functions in a line stack;

3. Any CPU registers contain pointer pointing objects;

The above root list is maintained by JIT and Clr and can be accessed by GC.

After the useless unit is recycled, GC starts to traverse the root, locate the object pointed to by the first root, locate the following object, locate all referenced objects of the object, and reference the object, and put it into a collection. After this is done, find the next root. Once the GC finds that an object is already in the collection, it stops searching for this branch to prevent repetition and reference endless loops.

After the collection is complete, GC has a set of all objects that can be accessed by the root, and no objects in this set are considered useless. For example:

The GC collection includes objects a, B, d, and F. Objects C, E, and g are useless objects, and GC releases their resources. GC then traverses all objects in the heap, releases useless objects, and moves useful objects to the memory (memcpy is said to be used) to ensure the continuity of idle space. Nextobjptr is directed to the starting address of the free space. This will invalidate the reference addresses of some objects, and GC is responsible for correcting these pointers. The collected heap is as follows:

This collection is not complicated, and the CPU time consumed is also large. But fortunately, it is not always running, but only collected after it is full (in fact, after the generation 0 is full, I willArticleDiscussed), other memory allocation is still very fast. In addition,. NET provides rich settings to improve the efficiency of useless unit recycling.

Finalize

In the previous article, I allocated a total of five steps to use resources. We already know how GC releases memory for useless objects. But how does it clear the resource usage status and release some non-memory system resources in Step 4 ?. NET introduces Fina

GC finds that an object has fina when useless units are recycled.

We can use two methods to write our fina

Code 1

Pub

{

Pub

{

}

 

Protected override void Fina

{

Console. writeline ("Fina

}

}

Note that. NET will not help you call the FINA of the base class.

Code 2

Pub

{

Pub

{

}

 

Protected override void Fina

{

Console. writeline ("Fina

Base. Fina

}

}

Another method is destructor. The destructor in C # are different from those in C ++. Let's look at the following code:

Code 3

Pub

{

Pub

{

}

 

~ Someclass ()

{

Console. writeline ("Fina

}

}

It is equivalent to Code 2.

Use Fina

How does GC implement Fina?

When the memory of the managed heap is insufficient, GC starts to recycle the heap. Check Fina before GC recycles an object.

Object g and Object E are not in the root range and are recycled. Object F and Object C need Fina

At this time, object F and Object C are no longer part of the root. If GC is recycled at this time, it will be regarded as useless objects for recycling. After the collection, such:

The above briefly describes Fina

LGeneration

Each time the entire pair is searched, compression is very time-consuming. Microsoft has summarized some of the past development phenomena. One of them is that the newer the object, the sooner it is discarded and no longer used. Based on this experience, Microsoft introduced the concept of generation in memory recycling. I will translate it into a generation now. When the managed heap starts, it is empty. When the program starts to allocate objects in it, the object is the 0th generation (generation 0) object. For example:

Next, when there is not enough space in the managed heap, GC recycles for the first time, and the remaining unrecycled objects are promoted to the first generation, and then the newly allocated objects are the 0th generation (FIG ). If GC is then recycled, only the first generation will be recycled. The second generation will be upgraded to the first generation, and the first generation will be upgraded to the second generation (Figure B ).

The default generation (generation) of GC is up to 2, and will not be upgraded after the upgrade to the second generation. So when will GC be the first and second generation? After GC recycles the first generation, if the memory space is not enough, the first generation will be reclaimed. If the first generation is not enough, the second generation will be reclaimed.

This article also writes a lot, so the next article continues, the next article writes weakreference and how to control GC actions in your own code.

This article goes on to discuss other topics about useless Resource Recycling last time.

L weakreference)

We usually use strong references of objects. If strong references exist, GC will not recycle objects. Can we keep the reference to the object at the same time, and let the GC reclaim this object as needed ?. NET provides weakreference for implementation. Weak references are easy to use. See the following code:

code 1

Object OBJ = new object ();

weakreference Wref = new weakreference (OBJ );

OBJ = NULL;

The first line of code creates a new object called object A. obj is a strong reference to object. The second line of code creates a weak reference object. The parameter is the strong reference of object A, and the third line of code releases the strong reference to object. If GC is recycled, object A is recycled.

How can we obtain strong references from object? Very simple. Please refer to Code 2:

Code 2

Object OBJ 2 = Wref. Target;

If (obj2! = NULL)

{

... // Do what you want to do.

}

else

{

... // The object has been recycled. If you want to use it, you must create a new one.

}

As long as the displayed target attribute with a weak reference value is attached, a strong reference of the object represented by the weak reference will be obtained. However, before using an object, check its availability because it may have been recycled. If you get null (nothing in VB. NET), it indicates that the object has been recycled and cannot be reused. You need to allocate a new one. If it is not null, you can use it with confidence.

Next, let's take a look at another version of weakreference. See Code 3:

Code 3

 //  pub  

// Object Target ,

// bool trackresurrection

//);

Object obj1 = new object ();

Object obj2 = new object ();

weakreference wref1 = new weakreference (obj1, false);

weakreference wref2 = new weakreference (obj2, true );

Another weakreference version has two parameters. The first parameter is the same as the previous version. Let's take a look at its prototype, bool trackresurrection. Tracking and resurrection is a bool type, that is, whether to trace the resurrection. I mentioned in the previous article that FINA is required.

Now let's see how weakreference is implemented. Obviously, weakreference cannot directly reference the target object. The get/set function of the Target attribute of weakreference is two functions, and the reference of the target object is returned from somewhere, instead of directly returning or setting a private variable as we usually write. GC maintains two lists to track the target objects with two weak references. When a weakreference object is created, it finds a location in the corresponding list and places the reference of the target object, obviously, these two lists are not part of the root. When GC is used to recycle memory, if an object is to be recycled, the list of weak references will be checked. If the reference of this object is saved, it will be set to null.

LControl GCAction

. NET provides the system. GC class to control GC behavior. GC only provides static methods and does not need or need to (GC constructor is made private) create its instance.

The main method provided by the GC class is collect, which makes it possible to control memory collection. The collect method has two versions: voidCollect(); And voidCollect(INT );. The second version of collect provides a parameter that allows you to choose to recycle the generation (generation) and the objects of other users, that is, GC. collect (0) only recycles 0th generations of objects, while GC. collect (1) is to recycle objects of the first and second generations. Collect () is to recycle all objects, which is equivalent to GC. Collection (GC. maxgeneration ). Maxgeneration is the only property of GC, which provides the highest generation of GC.

The GC class provides another method to obtain the object's generation value, getgeneration. Code 4 provides an example code to better understand the two methods provided by generation and GC. See Code 4:

Code 4

Class gcdemoclass

{

~ Gcdemoclass ()

{

Console. writeline ("demo class Fina

}

}

Static void

{

Gcdemoclass inst = new gcdemoclass ();

 

Console. writeline ("generation of demo object: {0}", GC. getgeneration (insT ));

 

GC. Collect ();

 

Console. writeline ("generation of demo object: {0}", GC. getgeneration (insT ));

 

GC. Collect ();

 

Console. writeline ("generation of demo object: {0}", GC. getgeneration (insT ));

 

Inst = NULL

GC. Collect (0 );

Console. writeline ("after collect generation 0 ...");

 

GC. Collect (1 );

Console. writeline ("after collect Generation 1 ...");

 

GC. Collect (2 );

Console. writeline ("after collect generation 2 ...");

 

Console. Readline ();

}

Gcdemoclass implements an destructor. As mentioned in the previous article, the compiler will change it to Fina.

GC also provides other methods, which will not be discussed here. You can refer to msdn.


Self: http://www.upschool.com.cn/edu/1317/2005/528/10du246616_1.shtml

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.