Implement a custom memory cache for image loading in Android.
Instruction: Design and describe the implementation of a custom memory cache system for efficiently loading and caching images in an Android app, including cache eviction policies.
Updated
Example design
Use LruCache<ImageKey, Bitmap> for a memory-only cache, and document its size unit. A least-recently-used policy evicts the least recently accessed entries when the configured budget is exceeded; it is not a disk cache or a guarantee that total process memory stays below that budget.
- Choose a measured budget. Pass the maximum in bytes and override
sizeOf(key, bitmap)to return a byte cost in the same unit. On supported modern Android versions,Bitmap.getAllocationByteCount()measures the pixel allocation and can exceedgetByteCount()after reuse. Keep cached bitmaps immutable in size and use a budget representable byLruCache's integer API. The defaultsizeOfcounts entries, so passing a byte budget without an override does not enforce a byte limit. A fraction such as one eighth of the heap is only a starting heuristic. - Key the decoded variant. Include source identity/version and the requested dimensions, transformation and relevant configuration. A URL alone is insufficient if two requests need different decoded images.
- Load outside the UI thread. Check the cache, then coalesce concurrent misses for the same key and bound decoding/network work. Individual
LruCacheoperations are thread-safe, but a get-then-load sequence is not automatically one atomic load. Do not hold a cache lock while performing network or decoding work. - Handle oversize entries and eviction. Skip caching an image larger than the budget. On eviction, release the cache's reference; do not automatically call
recycle()while a view or another owner may still use the bitmap. A displayed bitmap can remain alive after eviction. - Respond to lifecycle and pressure. Cancel obsolete view requests, reduce or clear the cache when appropriate, and account separately for displayed images, in-flight decodes and other memory. A production loader can provide these facilities without maintaining a custom implementation.
For a hypothetical 4 MiB budget, insert A at 3 MiB and B at 1 MiB, then access A and insert C at 1 MiB. B is now least recently used and is evicted; A and C total 4 MiB. A single 5 MiB image should bypass this cache. Test replacement of an existing key, simultaneous misses, distinct size variants and eviction while an image is displayed.
Sources
LruCache sizing and thread safety; Bitmap allocation size; bitmap ownership and recycling.