Thursday, September 29, 2011

Weak Reference

For performance reasons, you typically want to keep the cpu expensive stuffs loaded in cache, so that everytime that does not need to be computed. Caching the images is perhaps the most common example.

But you surely don't want to keep that heavy images loaded forever. At some point, when no body is using it, you want it removed. A non-strong reference, for example, Soft reference or Weak reference, comes very handy in caching. Unfortunately CLDC1.1 does not support soft reference, you can rely on weak reference only. CLDC 1.0 supports none (but probably none but grandpas use CLDC1.0 devices, and hopefully you are not writing an app for them).

Using a Weak reference cannot be any simpler.


WeakReference weakRef = new WeakRefernce(null);

public void putToCache(Image data) {

   weakRef = new WeakReference(data);

}



public Object getUsingCache() {

  Image data = (Image) weakRef.get();

  if (data == null) {

     data = createImage();

     putToCache(data);

  }

  return data;

}


By the way, For Android, there is a little (!) problem... check http://code-gotcha.blogspot.com/2011/09/softreference.html

No comments:

Post a Comment