Weak, Soft and Phantom References

Bob Lee posted yesterday about one of his sessions at Javapolis (viewable at Parley’s), that covered heaps of good stuff about dependency injection and API design. At the end he mentions weak and soft references. What? Who? Not exactly a language feature that I have come across in the day to day, so I did a quick search and came up with this:

A weak reference is a reference that isn’t strong enough to force an object to remain in memory.

Hopefully, I can give a better explanation than that.

A strong reference is one that while it exists, the object won’t get garbage collected:

Goat goat = new Goat();

If the goat is referenced elsewhere and loses all other references, it will still stay in memory. This is a problem if you want to keep some other data around about the goat:

Map<Goat, GoatInfo> goatMetaData = new HashMap<Goat, GoatInfo>();
goatMetaData.add(goat, new GoatInfo("Billy"));

To ensure that you don’t keep goats around any longer than you have to, you would have to do some weird coding to ensure that that code that deals with goats cleans up the store. Something with listener classes or similar.

Enter the weak reference. You wrap your goat in it as such:

WeakReference weakGoat = new WeakReference(goat);
Goat goat = (Goat) weakGoat.get();

Alternatively:

WeakReference<Goat> weakGoat = new WeakReference<Goat>(goat);
Goat goat = weakGoat.get();

weakGoat will return null, once all the other references to goat have been set to null, and it has been garbage collected.

So that’s cool for a single instance. What about the metadata example above? Well, there is a Map implemenation that uses this feature.

Map<Goat, GoatInfo> goatMetaData = new WeakHashMap<Goat, GoatInfo>();
goatMetaData.add(goat, new GoatInfo("Billy"));

If you try to get the additional info about the goat once it has been garbage collected, the map will return null. Nifty.

Soft reference objects, on the other hand are cleared at the discretion of the garbage collector in response to memory demand. So while weak references will be cleaned when the garbage collector deems that the underlying object has gone, use of soft references means that they will hang around a bit longer until the memory space is needed for something else.

An object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed. According to the API, they are “most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism”.

The API has much more detail on how to use this, although it’s kind of tough to get your head around. Too many uses of the word “reference”.

Useful when you are writing a container or cache. But you don’t want to do that because you know that you can get open source ones off the shelf, right? 😉

Nice one to know for interviews. Real bastard to ask 🙂

—- Update 25/04/08

I got asked 🙂


Posted

in

by