[Android] Using LruCache to cache Bitmaps and limit memory usage

Bitmaps are very bulk objects, loading them from the Internet or local storage could be expensive and “choke” the UI. You want to  keep them in memory so that they could be loaded instantly, however you also want to discard them as soon as they are not useful. Here comes the LruCache.

What is LruCache?

LruCache is a util introduced in API 12, which is an implementaion of the Least Recently Used cache. In short, that is a caching strategy which the “oldest” entries are discarded when overflow occur. It is very useful to cache Bitmaps. The default implementation allows you to limits the number of items in the cache. Here’s how to slightly modify the LruCache to limit the memory usage of the cache.

How to use it?

Well, actually it act just like a HashMap.

Control Memory usage

Limiting the LruCache size by their count may not seemed useful when you are caching Bitmaps because they varies in size. If you set the cache size to 20, you could easily get OutOfMemoryError if the bitmaps are 2MBs each! What worse is that the LruCache now maintains a hard reference to the Bitmaps so they cannot be GC! We definitely need to limit the memory usage of the cache. Good news is that the LruCache class has a sizeof() method which you can override. Redefine the “size” to measure num of bytes and you’re done.

Full code of the Class:

Note that I use String as the type of the key, since I use it to map URL->Bitmap. You can change to whatever you want.

For Compatibility

If you need to be compatible with old API levels, this is an imporved version. You need to import the compatibility library, and since the getByteCount() method is not available until Honeycomb, you need to check for that also.

Share your thoughts