Monday, December 31, 2012

Java WeakReference, SoftReference and WeakHashMap

Strong reference

A strong reference is an ordinary Java reference. Usually Java references will be implemented as pointers, but that's not required by the language specification. They may be using an additional layer of indirection to enable easier garbage collection. References interacts with garbage collector.  Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. This is normally exactly what you want.

Weak reference

One problem with strong references is caching, particular with very large structures like images, sounds, etc. Cache is common source of memory leaks. Once you put an object reference into a cache, it’s easy to forget that it’s there and leave it in the cache long after it becomes irrelevant. 

To solve this problem you need to implement a cache for which an entry is relevant exactlyso long as there are references to its key outside of the cache.

Weak reference leverage the garbage collector's ability to determine reachability for you.

You can create and use Weak reference like this (for some imaginary Car object and car object instance):

//Create weak car reference.
WeakReference<Car> weakCar = new WeakReference<Car>(car);
//Then to get actual car instance use following:
Car weakCarRef = weakCar.get();
 Weak reference isn't strong enough to prevent garbage collection, so you may find that .get() suddenly starts returning null. Which is basically what you want in the first place, but usually WeakReferences are used together with WeakHashMap class.

In WeakHashMap entries will be removed automatically after they become obsolete. Remember that WeakHashMap is useful only if the desired lifetime of cache entries is determined by external references to the key, not the value.

Using WeakHashMap is simple because it uses same Map interface that is used for HashMap and all basic Map data structures in Java.

Soft reference

soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. In practice softly reachable objects are generally retained as long as memory is in plentiful supply.

Use it or not to use it?
Personally I don't like weak, soft and phantom references because you basically hand control of you program to GC and he will decide when is the time to remove reference, not you. 

No comments:

Post a Comment