Designed for Android caching
Preface to Android Cache Design
Android, a memory-sensitive system, inevitably needs to use caching when processing a large number of images. In the end, it should use the SoftReference guaranteed by GC at the underlying layer of the virtual machine, or is it better to use a queue with LRU Algorithm for Android applications?
Basic Concepts
Cache, as its name implies, stores the data that has been read for further reading. The rational use of cache can reduce some expensive actions (Database Operations, file read/write, network transmission, etc ), ease system pressure and increase program response speed.
There are several considerations for designing cache: cache capacity, how to keep the cache in a proper size (processing of expired cache, processing of excess capacity), and how to handle concurrency.
Implement SoftReference LRU Queue Official Google practices implement cache based on SoftReference
Here, when an image is obtained based on the image url and converted to Bitmap, two levels of cache are implemented: the first level is the memory cache. Here, HashMap is used to save the soft reference of Bitmap, and the key is the url; another level is persistent cache, where file storage (or database storage) is used ).
Let's take a look at the main code:
SoftReference currBitmap = imageCaches. get (url); Bitmap softRefBitmap = null; if (currBitmap! = Null) {softRefBitmap = currBitmap. get () ;}...... // get data from soft reference first if (currBitmap! = Null & mImageView! = Null & softRefBitmap! = Null & url. equals (mImageView. getTag () {mImageView. setImageBitmap (softRefBitmap);} // No soft reference, get data from the file else if (bitmap! = Null & mImageView! = Null & url. equals (mImageView. getTag () {mImageView. setImageBitmap (bitmap);} // the file does not exist either. In this case, the creation thread obtains data from the network else if (url! = Null & needCreateNewTask (mImageView) {MyAsyncTask task = new MyAsyncTask (url, mImageView, download); if (mImageView! = Null) {task.exe cute (); // Save the task corresponding to the corresponding url to map. put (url, task );}}