WeakReference weak references in Android

Source: Internet
Author: User

WeakReference Weak references

Definition: A weak reference, as opposed to a strong reference (the common way we refer to it), is characterized by that the GC ignores the weak reference object when it is reclaimed (ignoring this referential relationship), that is, even if the weak reference points to an object, the object will be reclaimed by GC when it is not pointed to by a strong reference.

Strong reference instances are naturally not recycled by GC!

How do I elicit a weak reference? What is the actual use of weak references?

What is a memory leak? Java uses a forward graph mechanism to automatically check objects in memory through a GC, and if the GC discovers a State or group of objects that are unreachable, the object is reclaimed from memory. That is, if an object is not pointed to by any reference, the object is recycled when it is discovered by the GC.

Instances that may cause a memory leak:

    Handler Mhandler = new Handler () {        @Override public        void Handlemessage (Message msg) {            Mimageview.setimagebitmap (mbitmap);};    

When using an inner class (or an anonymous class) to create a handler, the handler object implicitly holds a reference to an external class object (usually activity) (otherwise, how can the activity view be manipulated by handler?). )。 Handler typically accompanies a time-consuming background thread (such as pulling a network image), which notifies handler via a message mechanism after the task has been executed, and handler updates the image to the interface. Assuming that the user shuts down the activity during a network request, it is possible that the activity is no longer being used and is likely to be recycled by GC, but the thread has not been executed yet, and the thread holds the handler reference (how else can I send a message to handler?). ), handler also holds the activity reference, which causes the activity to not be recycled (memory leaks) until the end of the network request (for example, the picture has been downloaded). In addition, if Handler's postdelayed () is executed, the method loads the handler into a message and pushes the message into the MessageQueue, resulting in a chained structure:messagequeue-> Message->handler->activity, which causes the Activity to be held by reference and cannot be recycled. (Summary: Instance objects are referenced by other objects and cannot be recycled)

What are the dangers of memory leaks? A memory leak can cause the virtual machine to consume too much memory. For Android applications, users open an activity, shut down after use, memory leaks, perform the above steps several times, the program consumes more memory than the system limits.

How do I avoid memory leaks? What methods can I use? This leads to a weak reference.

For non-required objects, objects associated with weak references can only survive until the next GC occurs. When the GC is working, the objects associated with the weak reference are reclaimed regardless of whether the current memory is sufficient.

/** * < function description > for loading bitmap instance *  * @author Administrator */public class Asyncdrawable extends Bitmapdrawable {    PR Ivate final weakreference<bitmapworkertask> bitmapworkertaskreference;    Public Asyncdrawable (Resources res, Bitmap Bitmap,            bitmapworkertask bitmapworkertask) {        super (res, Bitmap);        Bitmapworkertaskreference Instance association bitmapworkertask        bitmapworkertaskreference = new weakreference< Bitmapworkertask> (                bitmapworkertask);    }    Public Bitmapworkertask Getbitmapworkertask () {        return bitmapworkertaskreference.get ();    }}

At this point weakreference<bitmapworkertask> bitmapworkertaskreference is associated with the Bitmapworkertask instance (which can be considered a "good friend" relationship); in the virtual machine it seems Bitmapworkertask instances are garbage, but weakreference<bitmapworkertask> bitmapworkertaskreference is not garbage. However, the garbage is not immediately recycled, that is, the object Bitmapworkertask instance can still be used, and if the object has been cleaned, the object must be rebuilt and associated again.

The advantage is that you can apply any number of Bitmapworkertask instance objects and associate them with weakly referenced objects, determine if they have been released before use, and if they have been released, re-apply, or use them directly if they are not released. WeakReference is responsible for releasing the rules.

With the above code in place, after the user has closed the activity, even though the background thread is not finished, all GC will still recycle the activity while checking because only one weak reference from handler points to the activity.

WeakReference weak references in Android

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.