Image processing for Android development (i): Building a picture cache with soft references

Source: Internet
Author: User

In Android development, picture processing is a difficult point. For a lot of picture processing, accidentally will appear oom error. Then, building the cache is a very necessary means. Building the cache with soft references is just one of the steps, let's take a look at the general process of drawing processing.

Generally speaking, the process of image processing is roughly the same as the previous xutils principle. Today, let's talk about how to build a cache using soft-reference technology.


Four types of references to objectsIn previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.


1, Object strong reference (Strongreference)Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
2. Object soft Reference (SoftReference)if an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches (see below for an example).
A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.
3, Object weak reference (WeakReference)the difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references. A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.
4.Virtual Reference (phantomreference)"virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.
Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory.
Referencequeue queue = new Referencequeue ();
Phantomreference PR = new Phantomreference (object, queue);
The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program discovers that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.
Second, the use of soft references1. Why use soft references
After understanding four references, let's say why we use soft references. Take Picture object bitmap as an example. First, we'll use a ListView to view some of the columns ' pictures. As a user, we completely need to scroll up and down to see the different pictures. At this point we usually have two ways to implement the program: one is to save the picture objects that have been viewed in memory, the life cycle of each Java object that stores the picture information throughout the application, and the other is when the user starts to view other picture information, The end reference of the Java object, which stores the current picture information, allows the garbage collection thread to reclaim the memory space it occupies and reconstruct the image information when the user needs to browse the picture information again. Obviously, the first implementation will result in a lot of memory waste, and the second implementation is flawed even if the garbage collection thread is not garbage collected, the object containing the picture information remains intact in memory, and the application is rebuilding an object. We know that access to disk files, access to network resources, query databases and other operations are important factors affecting the performance of application execution, if you can regain those who have not yet been recycled Java object references, will reduce unnecessary access, greatly improve the speed of the program. And this time, the use of soft reference technology.
2. How to use soft referencesThe SoftReference feature is that an instance of it holds a soft reference to a Java object, and the existence of the soft reference does not prevent the garbage collection thread from reclaiming the Java object. That is, once SoftReference has saved a soft reference to a Java object, the Get () method provided by the SoftReference class returns a strong reference to the Java object before the garbage thread recycles the Java object. Also, once a garbage thread reclaims the Java object, the Get () method returns NULL.
Look at the following code:
MyObject aRef = new MyObject ();
SoftReference asoftref=new SoftReference (AREF); At this point, for this MyObject object, there are two reference paths, one is a soft reference from the SoftReference object, and one is a strong reference from the variable areference, so this MyObject object is a strong object.
We can then end Areference's strong reference to this MyObject instance: ARef = null;
Since then, the MyObject object has become a soft and accessible object. If the garbage collection thread is in memory garbage collection, it does not always retain the object because it has a softreference reference to the object. The Java Virtual machine's garbage collection thread treats soft-and object-and other generic Java objects differently: The cleanup of soft and object is determined by the garbage collection thread according to its memory requirements based on its particular algorithm. That is, the garbage collection thread reclaims the soft objects before the virtual machine throws OutOfMemoryError, and the virtual machine takes priority to reclaim the soft objects that are unused for long periods of time, and the "new" soft-anti-objects that have just been built or used are retained by the VM as much as possible. Before reclaiming these objects, we can pass: MyObject anotherref= (MyObject) asoftref.get (); Regain a strong reference to the instance. After the collection, the call to get () method can only get null.
3. Use Referencequeue to clear the softreference of the Lost soft reference object

As a Java object, the SoftReference object has the generality of Java objects in addition to the particularity of saving soft references. So, when a soft and an object is recycled, although the get () method of the SoftReference object returns NULL, the SoftReference object no longer has the value of being present and requires an appropriate cleanup mechanism. Avoid memory leaks caused by a large number of SoftReference objects. The Referencequeue is also available in the Java.lang.ref package. If a SoftReference object is created, a Referencequeue object is used as the constructor for the softreference, such as:
Referencequeue queue = new Referencequeue ();
SoftReference ref=new softreference (amyobject, queue);
Then when the SoftReference soft-referenced amyohject is reclaimed by the garbage collector, ref's strongly referenced SoftReference object is included in the Referencequeue. That is, the object saved in Referencequeue is the reference object, and it is the reference object that has lost the object it is soft referenced. Also from the name of Referencequeue, it is a queue, when we call its poll () method, if this queue is not empty queue, then will return the queue in front of the reference object.
At any time, we can call Referencequeue's poll () method to check if there are non-strong objects that it cares about being recycled. If the queue is empty, a null is returned, otherwise the method returns a reference object in front of the queue. Using this method, we can check which softreference the soft reference object has been recycled. So we can get rid of the SoftReference objects that have lost the soft reference object. The usual ways are:
SoftReference ref = NULL;
while (ref = (EMPLOYEEREF) q.poll ()) = null) {
Clear ref
}
After understanding Referencequeue's working mechanism, we can begin to construct a cache of Java objects.


Third, build image processing object image cache1. Image Object Instance
Package Org.cao.optimization.util;import Java.io.file;import Org.cao.optimization.constantvalue;import Android.graphics.bitmap;import Android.os.environment;public class Image {//Picture idprivate String id;// The picture corresponds to the Bitmap object private Bitmap bitmap;public image (String ID, Bitmap Bitmap) {super (); this.id = Id;this.bitmap = Bitmap;} Public Image (String id) {this.id = ID;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public Bitmap Getbitmap () {return Bitmap;} public void SetBitmap (Bitmap Bitmap) {this.bitmap = Bitmap;} /** * @Title: HasFile * @Description: Determine if there is a picture in the local SD * @param ID * @return * @throws */public static Boolean hasFile (String ID) {Boolean result = false;//Determines whether there are related files in the local sdcard if (Environment.getexternalstoragestate (). Equals (Environment.media_ Mounted)) {File externalstoragedirectory = Environment.getexternalstoragedirectory (); String path = Externalstoragedirectory.getabsolutepath () + Constantvalue.image_path; File dir = new file (path); file[] Listfiles = dir.listFiles (); if (listfiles! = null && listfiles.length > 0) {for (int i = 0; i < listfiles.length; i++) {if (list Files[i].getname (). StartsWith (ID)) {result = True;break;}}} return result;} /** * @Title: Getfilefromsdcard * @Description: Get pictures from SD card * @param ID * @param path * @param extend * @return * @throws * * public static file Getfilefromsdcard (string ID, string path, string extend) {file result = Null;if (Environment.getexterna Lstoragestate (). Equals (environment.media_mounted)) {File externalstoragedirectory = Environment.getexternalstoragedirectory ();p ath = externalstoragedirectory.getabsolutepath () + Path;result = new File ( New File (path), ID + extend);} return result;} /** * @Title: Getfilefromsdcard * @Description: Get pictures from SD card * @param ID * @return * @throws */public static File Getfilefrom SDcard (String ID) {return getfilefromsdcard (ID, constantvalue.image_path,constantvalue.png);}}

2. Image Object Cache Imagecache Construction
/** * @ClassName: Imagecache * @author victor_freedom ([email protected]) * @createddate 2015-1-30 pm 4:49:56 * @Descr Iption:image Object Cache */public class Imagecache {static private Imagecache cache;//a cache instance private hashtable<string, I Mageref> imagerefs;//for storage of Chche content private referencequeue<image> q;//garbage reference queue//inheritance softreference, So that each instance has an identifiable identity. Private class Imageref extends Softreference<image> {private String key = "";p ublic imageref (Image im, referencequeu E<image> q) {super (IM, q); key = Im.getid ();}} Build a cache instance private Imagecache () {imagerefs = new hashtable<string, imageref> (); q = new Referencequeue<image > ();} Get the cache instance public static Imagecache getinstance () {if (cache = = null) {cache = new Imagecache ();} return cache;} References an instance of an Image object as a soft reference and saves the reference public void Cacheimage (Image im) {Cleancache ();//Clears the garbage reference imageref ref = new Imageref (IM, Q); Imagerefs.put (Im.getid (), ref);} Retrieves an instance of the corresponding image object, based on the specified ID number, public image getImage (String id) {ImThe Age im = null;//cache has a soft reference to the image instance, if any, obtained from a soft reference. if (Imagerefs.containskey (ID)) {imageref ref = (IMAGEREF) imagerefs.get (id); im = (Image) ref.get ();} If there is no soft reference, or if the instance obtained from the soft reference is NULL, rebuild an instance,//and save the soft reference to the new instance if (IM = null) {im = new Image (ID); System.out.println ("Retrieve from Imageinfocenter. Id= "+ ID"; This.cacheimage (IM);} return im;} private void Cleancache () {Imageref ref = Null;while ((ref = (IMAGEREF) q.poll ()) = null) {imagerefs.remove (Ref.key);}} Clears all content in the cache public void ClearCache () {Cleancache (); Imagerefs.clear (); System.GC (); System.runfinalization ();}}

At this point, the cache of a picture object has been set up. I hope this article will help people who see this text. Next we're going to talk about the next steps in picture processing.


Image processing for Android development (i): Building a picture cache with soft references

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.