Analysis of Android Development optimization: Application of soft reference and weak reference _android

Source: Internet
Author: User

If an object has only a soft reference, the garbage collector does not reclaim it if there is enough memory space, and the memory of those objects is reclaimed if there is not enough memory. The object can be used by the program as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive caching. Soft references can be used in conjunction with a reference queue (Referencequeue), and if the soft reference references an object that is garbage collected, the Java Virtual machine adds the soft reference to the reference queue associated with it.

If an object has only a weak reference, when the garbage collector thread scans, it will reclaim its memory whenever it discovers an object that has only a weak reference, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a very low priority thread, it is not necessarily easy to find those objects that have only weak references. Weak references can also be used in conjunction with a reference queue (Referencequeue), and the Java virtual machine adds the weak reference to the reference queue associated with it if the object referenced by the weak reference is garbage collected.

The fundamental difference between weak references and soft references is that objects with only weak references have a shorter lifecycle and may be recycled at any time. Objects that only have soft references are recycled only when there is not enough memory, and are usually not recycled when memory is sufficient.

Several classes are provided in the JAVA.LANG.REF package: The SoftReference class, the WeakReference class, and the Phantomreference class, which represent soft, weak, and virtual references, respectively. The Referencequeue class represents a reference queue that can be used in conjunction with these three reference classes to track the activities of Java virtual machines that recycle referenced objects.

In the development of Android applications, soft references and weak reference techniques can be used as much as possible to prevent memory overflow and to handle objects with large memory footprint and long declaration periods.

The following is explained in detail using soft references. Weak references are used in the same way as soft references.

Suppose our application uses a large number of default images, such as the default avatar in the application, the default game icon, and so on, which are used in many places. If you read a picture every time, it's slower because it requires hardware to read the file, which can lead to lower performance. So we consider caching the picture and reading it directly from memory when needed. However, because the picture occupies a large memory space, caching many pictures requires a lot of memory, it may be more prone to outofmemory exceptions. At this point, we can consider using soft reference technology to avoid this problem.

First, define a hashmap and save the soft reference object.

Copy Code code as follows:

Private map<string, softreference<bitmap>> Imagecache = new hashmap<string, Softreference<bitmap >> ();

Then define a method to save the bitmap soft reference to HashMap.
Copy Code code as follows:

public void Addbitmaptocache (String path) {

Strong-Referenced Bitmap object

Bitmap Bitmap = bitmapfactory.decodefile (path);

Bitmap object for soft reference

softreference<bitmap> Softbitmap = new softreference<bitmap> (BITMAP);

Add the object to the map to cache it

Imagecache.put (path, softbitmap);

}


When obtained, the bitmap object can be obtained by softreference the Get () method.
Copy Code code as follows:

Public Bitmap Getbitmapbypath (String path) {

A bitmap object that takes a soft reference from the cache

softreference<bitmap> softbitmap = imagecache.get (path);

To determine if a soft reference exists

if (Softbitmap = = null) {

return null;

}

Remove the Bitmap object, if the bitmap is reclaimed due to insufficient memory, will get empty

Bitmap Bitmap = Softbitmap.get ();

return bitmap;

}


With soft references, the memory space of these cached picture resources can be freed up before the outofmemory exception occurs, thus avoiding the upper limit of memory and avoiding crash.

Note that before the garbage collector reclaims this Java object, the Get method provided by the SoftReference class returns a strong reference to the Java object, and the Get method returns null once the garbage thread reclaims the Java object. So in the code to get the soft reference object, it is important to judge whether it is null, lest the nullpointerexception exception will cause the application to crash.


Experience Sharing:

When do you use soft references and when do you use weak references?

Personally, you can use a soft reference if you just want to avoid outofmemory exceptions. If you care more about the performance of your application, and you want to reclaim some objects that are memory-intensive as soon as possible, you can use weak references.

And it is possible to judge by whether the object is often used. If the object is likely to be used frequently, use a soft reference as much as possible. If the object is less likely to be used, you can use a weak reference.

In addition, similar to the weak reference function is Weakhashmap. Weakhashmap for a given key, the presence of the mapping does not prevent the garbage collector from reclaiming the key, and its entries are effectively removed from the mappings after the recycle. Weakhashmap uses Referencequeue to implement this mechanism.

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.