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.