Open source reader

Monday, May 29, 2006

Understanding Weak References

Here is a great article from Ethan Nicholas about Weak references, here is what you'll read:
  • Strong references
  • When strong references are too strong
  • Weak references
  • Reference queues
  • Different degrees of weakness
  • Soft references
  • Phantom references
Here is an excerpt :
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 weakWidget = new WeakReference(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.

Happy reading !


Post a Comment

<< Home