When to use weak references

2 views
Skip to first unread message

Parag

unread,
Jul 16, 2007, 5:14:58 AM7/16/07
to Adaptive Learning
Hi Sanket,

Very nice question. We use weak or soft references when we want to
create an object, but do not mind losing it to the GC if the JVM runs
short on memory resources. Caches are a typical example. If we want to
cache some object for quick retrieval, we will hold it with a weak
reference. If the JVM runs short on resources it will reclaim the
objects memory, in which case we will have to re-instantiate the
object.

There is a specific data structure in Java to facilitate such
caches... are you game for a little treasure hunt?

You also asked, why can we not let the JVM decide the reference type
for us. This is because we do not want objects that we need to
disappear at random. Imagine what would happen if an Account object
was garbage collected while we were performing an operation on it.
Besides this if a needed object is GC'd, we end up losing it's state
which may cause the software to crash.

Hence by default all objects have strong references. Only disposable
objects (objects that are nice to have around but will not bring the
program down if they are GC'd) are created as softt or weak
references. The main practical example is an object cache for
immutable objects.

--
Regards
Parag

Sanket Daru

unread,
Jul 16, 2007, 5:40:07 AM7/16/07
to adaptive...@googlegroups.com
Dear Sir,
I went treasure hunting, am always game for it... :-)

WeakHashMap is the collection class that weak references its keys so that the memory can be reclaimed by GC as required.

Thanks for the insight. It helped dispel few doubts in my mind.

Regards,
Sanket Daru.
Reply all
Reply to author
Forward
0 new messages