Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What‘s the difference between short weak reference and long weak reference?

I know the knowledge below:

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.

So if the object has been reclaimed, you have to create it again when necessary.

Then, what's the difference between short weak reference and long weak reference? I think of it as below:(according to the msdn)

short weak reference: if GC reclaim the object, the object is really released.

long weak reference: if GC reclaim the object, the object is still existed (as it is cached).

So can someone tell me more detail?

like image 819
roast_soul Avatar asked Jul 09 '13 08:07

roast_soul


1 Answers

Short

The target of a short weak reference becomes null when the object is reclaimed by garbage collection. The weak reference is itself a managed object, and is subject to garbage collection just like any other managed object. A short weak reference is the default constructor for WeakReference.

Long

A long weak reference is retained after the object's Finalize method has been called. This allows the object to be recreated, but the state of the object remains unpredictable. To use a long reference, specify true in the WeakReference constructor.

If the object's type does not have a Finalize method, the short weak reference functionality applies and the weak reference is valid only until the target is collected, which can occur anytime after the finalizer is run.

To establish a strong reference and use the object again, cast the Target property of a WeakReference to the type of the object. If the Target property returns null, the object was collected; otherwise, you can continue to use the object because the application has regained a strong reference to it.

Guidelines for Using Weak References

Use long weak references only when necessary as the state of the object is unpredictable after finalization. Avoid using weak references to small objects because the pointer itself may be as large or larger.

Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.

Reference

like image 128
Amit Avatar answered Nov 09 '22 16:11

Amit