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

Source: Internet
Author: User

Java has divided object references into four levels since jdk1.2, so that the program can control the object lifecycle more flexibly. The four levels are from high to low: strong reference, soft reference, weak reference, and virtual reference.

Here we will focus on soft references and weak references.

If an object only has soft references, the garbage collector will not recycle it if the memory space is sufficient. 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. Soft references can be used together with a referencequeue, the Java virtual machine adds this soft reference to the reference queue associated with it.

If an object only has weak references, once the object with only weak references is found during the Garbage Collector thread scanning process, no matter whether the current memory space is sufficient or not, will recycle its memory. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references. Weak references can also be used together with a referencequeue, the Java virtual machine adds this weak reference to the reference queue associated with it.

The fundamental difference between weak references and soft references is that only objects with weak references have a shorter life cycle and may be recycled at any time. Objects with soft references are recycled only when the memory is insufficient. Normally, objects with soft references are not recycled when the memory is sufficient.

The Java. Lang. Ref package provides several classes: softreference class, weakreference class, And phantomreference class, which represent soft reference, weak reference, and virtual reference respectively. The referencequeue class indicates the reference queue, which can be used together with the three reference classes to track the activity of the referenced objects recycled by the Java Virtual Machine.

In the development of Android applications, to prevent memory overflow, when processing objects that occupy a large amount of memory and have a long Declaration cycle, you can try to apply soft references and weak references.

The following describes how to use soft references. The usage of weak references is similar to that of soft references.

Assume that our app will use a large number of default images, such as the app's default profile pictures and default game icons. These images will be used in many places. If you read an image each time, hardware operations are required to read the file, resulting in low performance. Therefore, we want to cache the image and read it directly from the memory when necessary. However, because the image occupies a large amount of memory and many images need a lot of memory to cache, The outofmemory exception may easily occur. At this time, we can consider using soft reference technology to avoid this problem.

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

Private Map <string, softreference <bitmap> imagecache = new hashmap <string, softreference <bitmap> ();

 

Define a method to save the soft reference of Bitmap to hashmap.

Public void addbitmaptocache (string path ){

// Strongly referenced bitmap object

Bitmap bitmap = bitmapfactory. decodefile (PATH );

// Soft referenced bitmap object

Softreference <bitmap> softbitmap = new softreference <bitmap> (Bitmap );

// Add the object to map to cache it

Imagecache. Put (path, softbitmap );

}

 

 

You can use the get () method of softreference to obtain the bitmap object.

Public bitmap getbitmapbypath (string path ){

// Obtain the soft referenced bitmap object from the cache

Softreference <bitmap> softbitmap = imagecache. Get (PATH );

// Determine whether soft reference exists

If (softbitmap = NULL ){

Return NULL;

}

// Retrieve the bitmap object. If bitmap is recycled due to insufficient memory, it will be null.

Bitmap bitmap = softbitmap. Get ();

Return bitmap;

}

 

After soft reference is used, before the outofmemory exception occurs, the memory space of these cached image resources can be released, so as to avoid Memory ceiling and crash.

Note that, before the Garbage Collector recycles this Java object, the get method provided by the softreference class will return a strong reference to the Java object. Once the garbage thread recycles this Java object, the get method returns NULL. Therefore, in the Code for obtaining soft reference objects, you must determine whether the value is null to avoid application crash due to nullpointerexception.

 

Experience Sharing:

When should I use soft references and weak references?

In my opinion, if you only want to avoid the occurrence of an outofmemory exception, you can use soft references. If you are more concerned about application performance and want to recycle objects that occupy a large amount of memory as soon as possible, you can use weak references.

In addition, you can determine whether the object is frequently used. If this object may be frequently used, try to use soft references. If this object is not used more likely, you can use weak references.

In addition, weakhashmap is similar to the weak reference function. For a given key, weakhashmap does not prevent the garbage collector from recycling the key. After the key is recycled, its entries are effectively removed from the ing. Weakhashmap implements this mechanism using referencequeue.

 

Blog related to optimization series:

Android development optimization-memory optimization for bitmap

Android development optimization-using soft references and weak references

Android development optimization-code optimization

Android development optimization-UI optimization (1)

Android development optimization-UI optimization (2)

Android development optimization-UI optimization (3)

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

Http://blog.csdn.net/arui319

An excellent solution for Android Application Development has been published. This article is part of the first draft. Welcome to purchase and read.

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

Thank you.

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

 

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.