Canonicalized Mapping

I have never understood the Java documentation for WeakReference, which says:

 Weak reference objects, which do not prevent their referents from being
 made finalizable, finalized, and then reclaimed. Weak references are
 most often used to implement canonicalizing mappings. 

What is a canonicalizing mapping, why would I use one and how do weak references help?


A "canonicalized" mapping is where you keep one instance of the object in question in memory and all others look up that particular instance via pointers or somesuch mechanism. This is where weaks references can help.

The short answer is that WeakReference objects can be used to create pointers to objects in your system while still allowing those objects to be reclaimed by the garbage-collector once they pass out of scope. For example if I had code like this:

 class Registry {
     private Set registeredObjects = new HashSet();

public void register(Object object) { registeredObjects.add( object ); } }

Any object I register will never be reclaimed by the GC because there is a reference to it stored in the set of registeredObjects. On the other hand if I do this:

 class Registry {
     private Set registeredObjects = new HashSet();

public void register(Object object) { registeredObjects.add( new WeakReference(object) ); } }

Then when the GC wants to reclaim the objects in the Set it will be able to do so.

You can use this technique for caching, cataloguing, etc. See below for references to much more in-depth discussions of GC and caching.


I had exactly the same question about weak references in Java, and Google brought me here. But the next entry was http://www.ociweb.com/jnb/archive/jnbJune2000.html, which is a lot clearer than Sun's.

Here's a better one from Sun I just found: http://developer.java.sun.com/developer/technicalArticles/ALT/RefObj/

And here's an in-depth discussion of Java garbage collectors: http://www.artima.com/insidejvm/ed2/gcP.html

(Sun caused the problem for us with stupid naming: the terms "soft", "weak" and "phantom" convey absolutely nothing relevant to anyone besides the person (smoking what?) who applied them to these classes.)

http://www.ezdefinition.com/cgi-bin/showsubject.cgi?sid=748 also discusses all three types of reference and their differences.


Contributors: TomRossen, IainLowe.


CategoryJava


EditText of this page (last edited May 12, 2013) or FindPage with title or text search