[Android] Android Development optimization-using soft references and weak references

Source: Internet
Author: User

Starting with the JDK1.2 version, Java is dividing the object's references into four levels, giving the program more flexibility in controlling the object's life cycle. These four levels are high to low in order: Strong references, soft references, weak references, and virtual references.

Here are some highlights of soft and weak references.

If an object has only soft references, the garbage collector does not recycle it if there is enough memory space, and the memory of those objects is reclaimed if there is insufficient memory space. 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. A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it.

If an object has only weak references, when the garbage collector thread scans, an object with only a weak reference will be 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 also 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 will add the weak reference to the reference queue associated with it.

The fundamental difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle 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 there is enough memory.

Several classes are available 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, which can be used in conjunction with these three reference classes in order to track the activity of the object referenced by the Java Virtual machine.

In the development of Android application, in order to prevent memory overflow, we can apply soft reference and weak reference technique when dealing with some objects that occupy large memory and have long declaration period.

The following is an example of using a soft reference as a detailed explanation. Weak references are used in a similar way to soft references.

Suppose our app uses a lot of default images, such as the default avatar in the app, the default game icon, and so on, which can be used in many places. If you read the picture every time, the slow speed of reading the file requires hardware operation, which results in lower performance. So we're thinking about caching the images and reading them directly from memory when needed. However, because the picture occupies a large memory space, caching many images requires a lot of memory, it is likely to be more prone to outofmemory exceptions. In this case, we can consider using soft-referencing techniques to avoid this problem.

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

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

To define a method, save the soft reference of bitmap to HashMap.

public void Addbitmaptocache (String path) {

Strongly-referenced bitmap objects

Bitmap Bitmap = bitmapfactory.decodefile (path);

Soft-referenced bitmap objects

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

Add the object to the map so that it is cached

Imagecache.put (path, softbitmap);

}

When obtained, the bitmap object can be obtained by softreference the Get () method.

Public Bitmap Getbitmapbypath (String path) {

To take a soft-referenced bitmap object from the cache

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

Determine if a soft reference exists

if (Softbitmap = = null) {

return null;

}

Remove the Bitmap object, if the bitmap is recycled due to insufficient memory, it 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, preventing the memory from reaching the upper limit and preventing crash from occurring.

It should be noted that the Get method provided by the SoftReference class returns a strong reference to the Java object before the garbage collector reclaims the Java object, and once the garbage thread reclaims the Java object, the Get method returns NULL. So in the code that gets the soft reference object, be sure to determine whether it is null in case the NullPointerException exception causes the application to crash.

Experience Sharing:

When to use soft references, when do you use weak references?

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

There is also can be based on whether the object is often used to judge. If the object is likely to be used frequently, use soft references as much as possible. If the object is more likely to be used, a weak reference can be used.

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

Optimization Series related blog posts:

Android Development Optimization--memory optimization for bitmap

Android Development optimization-using soft references and weak references

Optimized for Android development – from a code perspective

Android Development Optimization-UI optimization (1)

Android Development Optimization-UI optimization (2)

Android Development Optimization-UI optimization (3)

---------------------------------------------------------------------------

http://blog.csdn.net/arui319

The "Android Application development Solution" has been published, this article is part of the first draft. Welcome to buy Reading.

This article can be reproduced, but please keep the above author information.

Thank you.

---------------------------------------------------------------------------

    • Previous article 2012->2013
    • Next [Android] Android development optimization--from the code point of view to optimize

[Android] Android Development optimization-using soft references and weak 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.