Do SoftReference
and WeakReference
really only help when created as instance variables? Is there any benefit to using them in method scope?
If an object has only WeakReference
s (or no references whatsoever!) towards it, it can be garbage collected whenever Java needs to make more room in memory. So, you use WeakReference
s whenever you want an object to remain in memory, but you don't need it to remain THAT badly (e.g. if Java needs to garbage collect it, no problem, you can get it back somehow and in the mean time Java has better performance)
Enqueuing a WeakReference
allows you to iterate the ReferenceQueue
and determine which references have been garbage collected and which have not. That's all - so only do it if you need to know this.
Read more: http://weblogs.java.net/blog/2006/05/04/understanding-weak-references