Use SoftReference to cache image objects in Android

Source: Internet
Author: User

SoftReference in Java
Soft reference of an object. If an object has soft references and the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache. Using Soft references can prevent memory leakage and enhance program robustness.
SoftReference is characterized by a soft reference of a Java object saved by an instance. The existence of this soft reference does not prevent the garbage collection thread from reclaiming the Java object. That is to say, once SoftReference saves a soft reference to a Java object, the get () provided by the SoftReference class before the garbage thread recycles this Java object () method returns a strong reference to a Java object. In addition, once the garbage thread recycles the Java object, the get () method returns null

Cache soft referenced Bitmap objects with Map sets

Map <String, SoftReference <Bitmap> imageCache = new HashMap <String, SoftReference <Bitmap> ();
// Strongly referenced Bitmap object
Bitmap bitmap = BitmapFactory. decodeStream (InputStream );
// Soft referenced Bitmap object
SoftReference <Bitmap> bitmapcache = new SoftReference <Bitmap> (bitmap );
// Add the object to Map to cache it
ImageCache. put ("1", softRbitmap );
..
.

// Obtain the soft referenced Bitmap object from the cache
Softreference <bitmap> bitmapcache _ = imagecache. Get ("1 ");
// Retrieve the bitmap object. If bitmap is recycled due to insufficient memory, it will be null.

Bitmap bitmap _ = bitmapcache _. Get ();

If the program needs to load a large number of images from the Internet, then we will consider using a temporary folder on the sdcard to cache these images.

Related Article

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.