By the android cache design thought of preface
This memory-sensitive system of Android, when processing a large number of images will inevitably use the cache, so whether the virtual machine should be the bottom of the SoftReference through GC recovery, or use a queue with the LRU algorithm, Which is better for Android apps?
Basic concepts
Cache, as the name implies, has been read into the data to be read again, reasonable use of the cache can reduce some expensive actions (database operations, file read and write, network transmission, etc.), alleviate the system pressure, improve program response speed.
There are several aspects to be aware of when designing a cache: The capacity of the cache, how to keep the cache at an appropriate size (processing of expired caches, exceeding capacity processing), how to handle concurrency, and so on.
Practice
- SoftReference
- LRU Queue
- Google's official approach
Implementing caching based on SoftReference
Here to get the picture from the image URL and converted to bitmap, do two cache: the first level is the memory cache, the use of HashMap to save bitmap soft reference, key is the URL, and the other level is persistent cache, where the file storage (also can be replaced by database storage).
Let's take a look at the main code:
SoftReference currbitmap = imagecaches.get (URL); Bitmap softrefbitmap = null; if (currbitmap! = null) {Softrefbitmap = Currbitmap.get (); }......//first take data from soft reference if (Currbitmap! = NULL && Mimageview! = NULL && Softrefbitmap! = null && url.equals (Mimageview.gettag ())) {Mimageview.setimagebitmap (SOFTREFBITMAP); }//Soft reference not in, take data from file else if (bitmap! = null && Mimageview! = null && Url.equa LS (Mimageview.gettag ())) {Mimageview.setimagebitmap (bitmap); }//Not in the file, at which point the creation thread gets data from the network else if (URL! = null && needcreatenewtask (Mimageview)) {Myasy Nctask task = new Myasynctask (URL, mimageview, download); if (Mimageview! = null) {Task.execute (); Save the corresponding URL for the task map.put (URL, Task); } }
Designed by the Android cache