The Source for Java Technology Collaboration
User: Password:



Ethan Nicholas

Ethan Nicholas's Blog

Understanding Weak References

Posted by enicholas on May 04, 2006 at 05:06 PM | Comments (19)

Some time ago I was interviewing candidates for a Senior Java Engineer position. Among the many questions I asked was "What can you tell me about weak references?" I wasn't expecting a detailed technical treatise on the subject. I would probably have been satisfied with "Umm... don't they have something to do with garbage collection?" I was instead surprised to find that out of twenty-odd engineers, all of whom had at least five years of Java experience and good qualifications, only two of them even knew that weak references existed, and only one of those two had actual useful knowledge about them. I even explained a bit about them, to see if I got an "Oh yeah" from anybody -- nope. I'm not sure why this knowledge is (evidently) uncommon, as weak references are a massively useful feature which have been around since Java 1.2 was released, over seven years ago.

Now, I'm not suggesting you need to be a weak reference expert to qualify as a decent Java engineer. But I humbly submit that you should at least know what they are -- otherwise how will you know when you should be using them? Since they seem to be a little-known feature, here is a brief overview of what weak references are, how to use them, and when to use them.

Strong references

First I need to start with a refresher on strong references. A strong reference is an ordinary Java reference, the kind you use every day. For example, the code:

StringBuffer buffer = new StringBuffer();

creates a new StringBuffer() and stores a strong reference to it in the variable buffer. Yes, yes, this is kiddie stuff, but bear with me. The important part about strong references -- the part that makes them "strong" -- is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don't want the garbage collector destroying objects you're working on, this is normally exactly what you want.

When strong references are too strong

It's not uncommon for an application to use classes that it can't reasonably extend. The class might simply be marked final, or it could be something more complicated, such as an interface returned by a factory method backed by an unknown (and possibly even unknowable) number of concrete implementations. Suppose you have to use a class Widget and, for whatever reason, it isn't possible or practical to extend Widget to add new functionality.

What happens when you need to keep track of extra information about the object? In this case, suppose we find ourselves needing to keep track of each Widget's serial number, but the Widget class doesn't actually have a serial number property -- and because Widget isn't extensible, we can't add one. No problem at all, that's what HashMaps are for:

serialNumberMap.put(widget, widgetSerialNumber);

This might look okay on the surface, but the strong reference to widget will almost certainly cause problems. We have to know (with 100% certainty) when a particular Widget's serial number is no longer needed, so we can remove its entry from the map. Otherwise we're going to have a memory leak (if we don't remove Widgets when we should) or we're going to inexplicably find ourselves missing serial numbers (if we remove Widgets that we're still using). If these problems sound familiar, they should: they are exactly the problems that users of non-garbage-collected languages face when trying to manage memory, and we're not supposed to have to worry about this in a more civilized language like Java.

Another common problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.

Because an image cache is supposed to prevent us from reloading images when we don't absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you (just as above) to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. Once again you are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory.

Weak references

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

WeakReference<Widget> weakWidget = new WeakReference<Widget>(widget);

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

To solve the "widget serial number" problem above, the easiest thing to do is use the built-in WeakHashMap class. WeakHashMap works exactly like HashMap, except that the keys (not the values!) are referred to using weak references. If a WeakHashMap key becomes garbage, its entry is removed automatically. This avoids the pitfalls I described and requires no changes other than the switch from HashMap to a WeakHashMap. If you're following the standard convention of referring to your maps via the Map interface, no other code needs to even be aware of the change.

Reference queues

Once a WeakReference starts returning null, the object it pointed to has become garbage and the WeakReference object is pretty much useless. This generally means that some sort of cleanup is required; WeakHashMap, for example, has to remove such defunct entries to avoid holding onto an ever-increasing number of dead WeakReferences.

The ReferenceQueue class makes it easy to keep track of dead references. If you pass a ReferenceQueue into a weak reference's constructor, the reference object will be automatically inserted into the reference queue when the object to which it pointed becomes garbage. You can then, at some regular interval, process the ReferenceQueue and perform whatever cleanup is needed for dead references.

Different degrees of weakness

Up to this point I've just been referring to "weak references", but there are actually four different degrees of reference strength: strong, soft, weak, and phantom, in order from strongest to weakest. We've already discussed strong and weak references, so let's take a look at the other two.

Soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

SoftReferences aren't required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

Phantom references

A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?

The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be "resurrected" by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object.

What good are PhantomReferences? I'm only aware of two serious cases for them: first, they allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that. This isn't generally that useful, but might come in handy in certain very specific circumstances like manipulating large images: if you know for sure that an image should be garbage collected, you can wait until it actually is before attempting to load the next image, and therefore make the dreaded OutOfMemoryError less likely.

Second, PhantomReferences avoid a fundamental problem with finalization: finalize() methods can "resurrect" objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was "resurrected" during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

With PhantomReference, this situation is impossible -- when a PhantomReference is enqueued, there is absolutely no way to get a pointer to the now-dead object (which is good, because it isn't in memory any longer). Because PhantomReference cannot be used to resurrect an object, the object can be instantly cleaned up during the first garbage collection cycle in which it is found to be phantomly reachable. You can then dispose whatever resources you need to at your convenience.

Arguably, the finalize() method should never have been provided in the first place. PhantomReferences are definitely safer and more efficient to use, and eliminating finalize() would have made parts of the VM considerably simpler. But, they're also more work to implement, so I confess to still using finalize() most of the time. The good news is that at least you have a choice.

Conclusion

I'm sure some of you are grumbling by now, as I'm talking about an API which is nearly a decade old and haven't said anything which hasn't been said before. While that's certainly true, in my experience many Java programmers really don't know very much (if anything) about weak references, and I felt that a refresher course was needed. Hopefully you at least learned a little something from this review.


Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

  • weak references are essential, alot of associative memory leaks can be removed just by using those babies. I also use them in simple test cases to show that leaks have been removed.

    leouser

    Posted by: leouser on May 04, 2006 at 05:24 PM

  • Very nice blog entry. I was talking with the development manager of a large all-Java shop one time and I asked him about his need for profiling tools to track down memory leaks. He replied, "We seem to not have a problem with memory leaks since we started using weak references."

    Posted by: gsporar on May 04, 2006 at 06:57 PM

  • Good article. I must confess to being hazy as to the difference between Soft, Weak and Phantom - the API docs aren't terribly descriptive. It's also good to finally get some justification for why on earth anyone would want to use a PhantomReference.

    Posted by: skaffman on May 05, 2006 at 12:04 AM

  • Nice entry about a not too well known feature of Java that come quite handy.
    I fortunately discovered them long ago thanks to an article at java.com (when it was still called like that) and I've since used Soft References in a few occasions, like creating smart caches of pre-compiled objects (XSLT sheets in my case) that are able to be garbage collected if a sudden peak in memory usage occurs.

    You simply re-create them the next time you need them and if the memory usage has gone down, you go back to normal.

    I actually wrote an article about using Soft References for such purpose, but it's in spanish ;).

    Implementación de Caches Inteligentes Mediante "Soft References"

    Thanks again for spreading the knowledge!
    D.

    Posted by: greeneyed on May 05, 2006 at 04:57 AM

  • Good blog.
    I have also found LinkedHashMap very useful for caching.

    Posted by: abhijit_jadeja on May 05, 2006 at 06:46 AM

  • A very important use of PhantomReferences is in DGC (Distributed GC like in RMI). You most certainly do not want to perform remote notification in the GC thread.

    Posted by: ianschneider on May 05, 2006 at 08:56 AM

  • Very nice writeup indeed. I must admit I was unaware of phantom references. I heard somewhere that sun's jre does indeed treat soft references as weak references. Don't know if that's still (or ever really was) the case, but I remember reading it somewhere.

    One other common use of weak references is the WeakListener, which prevents an object from hanging around simply because another object is listening on it.

    Posted by: richunger on May 05, 2006 at 01:03 PM

  • I never really learned the difference between weak & soft until this guy ran into it: http://weblog.ikvm.net/PermaLink.aspx?guid=ec45dec2-ec22-4079-9b78-d06e15ddabe7


    Thanks for bringing up Phantom References, I don't think I'd ever heard of them.

    Posted by: ronaldyang on May 05, 2006 at 01:56 PM


  • In reply to the implicit question from richunger: The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.


    A nit: since JDK-1.5.0, the java.lang.ref.Reference class has been generified. So, to create one you use


    WeakReference<Widget> weakWidget = new WeakReference<Widget>(widget);


    and weakWidget.get() returns a Widget, just you'd expect.

    There are are some details about what the remove() method on a ReferenceQueue<Widget> returns, but I'll save that for my next job interview.

    Posted by: peterkessler on May 06, 2006 at 03:04 PM

  • Very well written article.

    One important gotcha about the WeakHashMap:
    Only the key is held by a WeakRefence. The value is held by a normal strong reference. If the value, therefore, holds a strong reference to the key (quite a common occurence), the item will never be removed. It would be nice to have a ReallyWeakHashMap that holds the values with a weak reference as well as the key.

    Posted by: neilswingler on May 06, 2006 at 11:55 PM

  • Hello all.

    I also spotted the "tech tip" on using weak references for listener lists. But I think this does not address exactly what it might imply. If you haven't seen that, the article is archived, here: http://java.sun.com/developer/JDCTechTips/2006/tt0211.html#1

    It explains implementing a weak reference collection in a Bean for storing added listeners. But in a typical use case, the client adding the listener does not retain a reference to the listener:

    class Client {
    public void foo() {
    someBean.addListener(new Listener() {
    public void event(Event e) {
    react();
    }
    });
    }
    void react() { ... }
    }

    Or by some similar means: specifically, where the client is not retaining a reference to this listener. The listener might refer to the client, and the client and listener might refer to the Bean, but those do not play into the associations being programmed by the weak reference: the reference will be dropped when nothing refers to the listener.

    So then in this Bean object, if the listener is retained weakly, it will effectively be a candidate for removal immediately, no? I don't see any code referring to the listener.

    Perhaps I have missed the intended usage, or another scenario. Can anyone clarify this for me?

    Thanks,
    Steev Coco.

    Posted by: steevcoco on May 08, 2006 at 11:53 AM

  • really really good article. thanks.

    Posted by: ludlow on November 09, 2006 at 09:47 PM

  • Great article. Weak-refs seem to be best kept secret. So useful, and so little used. I would like to add the following from JAVA API for WeakHashMaps: "This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator." So if your key objects override the equals method, WeakHashMaps may not be very useful.

    Posted by: amitabhgupta on February 25, 2007 at 01:38 PM

  • Hello. I would like to add a comment about PhantomReference. You wrote that: "PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object."
    Actually, according to JDK API docs this is not quite accurate: "Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable."
    So PhantomReferences MUST be cleared by hand, using clear() method, EVEN IF they always return null when you call get(). Otherwise, as long as PhantomReference objects are in memory (being strong referenced from root set objects), they referents are still there and consequently they are NOT "physically removed from memory" (even though they were being finalized and you cannot access them). Bottom of the line: if you do not clear() PhantomReferences by hand, you'll end up having memory leaks.

    Posted by: cryb on May 26, 2007 at 03:49 AM

  • This article from java.sun.com ( http://java.sun.com/developer/technicalArticles/ALT/RefObj/ )says the following -

    "Soft and weak reference objects are placed in their reference queue some time after they are cleared (their reference field is set to null). Phantom reference objects are placed in their reference queue after they become phantomly reachable, but before their reference field is cleared. This is so a program can perform post-finalization cleanup and clear the phantom reference upon completion of the cleanup. "

    While you have written the following -

    "The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be "resurrected" by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object."


    Isn't it completely opposite to what sun has said? Please let me know if I have missed something.

    Posted by: a_paul1 on August 06, 2007 at 07:09 PM

  • Yes, definitely useful, had not got my head around all of the different kinds of reference before

    Posted by: android5767 on October 10, 2007 at 03:47 AM

  • i had some questions about this and got a pretty good answers from someone who groks. I committed them to the blog for everyone to enjoy
    i hope this may be helpful to someone else

    Posted by: petvirus on November 29, 2007 at 06:43 AM

  • Thanks very much. Good article. But I am still confused by the difference between weak reference and phantom reference. However, it is not important, since I have known how to use weak reference, it is enough for my work now.

    Posted by: terry_xu on December 21, 2007 at 12:31 AM

  • Good article explaining why most people dont know or use weak references. Many programming and desing issues can be solved by 'back-doors' to the language. Weak references, are such a back-door. As the examples illustrate, the author is avoiding the effort needed to come up with a good design by relying on 'null' pointers at run-time! Code that uses such artifacts usually trade design issues for runtime issues. Such code is harder to debug or change. Reflection is another such back door. The resulting code is a lot harder to maintain, particularly when the original developer is not around :) Nice write-up though.

    Posted by: afarouk on February 26, 2008 at 05:11 AM



Only logged in users may post comments. Login Here.


Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds