Android using soft references and weak references for performance tuning tutorials

Source: Internet
Author: User

Java begins with the JDK1.2 version, dividing the object's references into four levels, allowing the program to control the object's lifecycle more flexibly. These four levels, from highest to lowest, are: Strong references, soft references, weak references, and virtual references.

Soft References

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.

Weak reference

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.

The code is as follows Copy Code
Private map<string, softreference<bitmap>> Imagecache = new hashmap<string, Softreference<bitmap >> ();



Then define a method to save the bitmap soft reference to HashMap.

The code is as follows Copy Code

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.

  code is as follows copy code

Public Bitmap Getbitmapbypath (String path) {

       //Bitmap object that takes a soft reference from the cache

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

       //Determine if there is a soft reference

         if (Softbitmap = null) {

            return Null

       }

       // Remove the Bitmap object, and if the Bitmap is reclaimed due to low memory, it will get an empty

        Bitmap Bitmap = Softbitmap.get ();

        return bitmap;

   }



After using soft references, the memory space of these cached picture resources can be freed before the outofmemory exception occurs, thus preventing memory from reaching the upper limit and avoiding the occurrence of 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, which 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.

summarizing:

When do I use soft references and when do I use weak references?
Personally, you can use a soft reference if you just want to avoid the occurrence of 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. The
also has to be judged by whether the object is frequently 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.
Additionally, similar to the weak reference feature 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.