Notes for weak Reference Applications

Source: Internet
Author: User

1. Introduction to weak references

In some cases, for example, when caching some big data objects, you may encounter a dilemma of memory and time. If you make large objects expire too quickly, each object creation consumes too much performance, on the contrary, if too many large objects are maintained, the memory will be exhausted, reducing the speed.

At this time ,. net (BCL) Weak reference (WeakReference) is available. If the memory is sufficient, GC will not recycle the memory occupied by large objects, so the weak reference is reachable, that is to say, this object can be reused for the purpose of caching. If the memory is insufficient, GC will have to recycle those large objects to release the memory space.

Of course, the premise to release these large objects is that there is no reachable reference (it will be regarded as a strong reference to emphasize the difference from weak reference ). In other words, the weak reference does not affect GC collection objects.

2. Issue

Let's take a look at this program:

        static void Main(string[] args)        {            WeakReference wr = GetWR();            while (wr.IsAlive)            {                Thread.Sleep(100);            }            Console.WriteLine("OK");            Console.ReadLine();        }        private static WeakReference GetWR()        {            object o = new object();            WeakReference wr = new WeakReference(o);            return wr;        }

It looks like this. The GetWR method gets a weak reference of an object. After exiting the method, all the strong references to this object will be gone. Theoretically, wr. isAlive changes to false at a certain time, that is, the object is recycled by GC. But when it runs, it is found that "OK" is not displayed at all. Why? Because no new object is created, GC has always considered that it does not need to be recycled, and then it is always an endless loop that does not seem to be an endless loop until one day GC becomes compassionate and recycles one.

So how can this code be modified to be correctly executed? It's not that GC will not be recycled. It's enough to forcibly recycle it. The simplest thing is to add a GC. Collect (), so that the loop can exit when appropriate.

3. Disadvantages

GC. the Collect () method solves the infinite loop problem, but it involves another problem: GC. collect () itself is a relatively expensive operation. If a full-generation recovery is performed every 0.1 seconds, it doesn't matter if the small program is used, but the program in the service class will not work, and this performance will be slowed down, in addition, full recovery will also undermine the residence of large objects that are expected to stay in the memory for as long as possible (that is, the correct way to use them at the beginning), so the disadvantages are not small. Therefore, we should avoid such applications when using weak references as much as possible:

  • The foreground thread uses a loop and the exit condition is that a weak reference cannot be reached.

If this method is used, all foreground threads are required when the entire application ends. If one of the foreground threads appears. isAlive) code, you need to wait for GC to recycle weak referenced objects. However, GC collection is usually uncontrolled (it may be very fast or long), that is, this front-end thread may survive for a long time, and because it is a front-end thread, the process will survive for such a long time (for the user, the program cannot be shut down ).

 

PS: after using the Paste As VS Code plug-in for a long time, we finally found a drawback: Host OS (win2003) the Code copied in VS cannot be pasted to the Guest OS (win 7 in Virtual Box) using this plug-in. Of course, this cannot be considered a defect, it can only be said that it is a small pity on Virtual Machine Applications.

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.