Android soft references and weak references
1. Softreference<t>: Soft Reference--> when the virtual machine is out of memory, the object it points to is recycled, and the Get method can be invoked when an object is needed.
2. Weakreference<t>: Weak reference--> may be reclaimed by the garbage collector at any time, not necessarily until the virtual machine is low on memory to force recycling. You can also call the Get method when you want to obtain an object.
3. WeakReference is generally used to prevent memory leaks, to ensure that the memory is recycled by virtual machines, SoftReference used to implement caching mechanism (cache);
Instance SoftReference
If an object has only a soft reference, it is similar to a dispensable daily necessities. If the memory space is sufficient, the garbage collector will not recycle it, and if the memory space is insufficient, the memory of those objects will be reclaimed. 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.
For example, in the picture loading frame, a weak reference is used to implement the memory cache.
Package com.stevenhu.lit;
Import java.lang.ref.SoftReference;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Map;
Import android.graphics.drawable.Drawable;
Import Android.os.Handler;
Import Android.os.Message;
Implementation of the picture asynchronous load class public class Asyncimageloader {//URL as the key, SoftReference as a value, establish a cache HashMap key value pairs. Private map<string, softreference<drawable>> Mimagecache = new hashmap<string, softreference<drawab
Le>> (); Implementation of the picture asynchronous load public drawable loaddrawable (final String imageUrl, final Imagecallback callback) {//query cache, view the currently required download of the picture is No in Cache if (Mimagecache.containskey (IMAGEURL)) {softreference<drawable> SoftReference = Mimagecache.get (
IMAGEURL);
if (softreference.get ()!= null) {return softreference.get (); } final Handler Handler = new Handler () {@Override public void DispatchMessage (message ms g) {//callback Imagecallbackimpl in the Imageload method, executed in the mainline (UI thread).
Callback.imageload ((drawable) msg.obj);
}
};
* If there is no cache, a new thread, used to download pictures from the network, * and then the acquired drawable sent to the handler processing, through the callback implementation in the UI thread to display the captured picture * * New Thread () {
public void Run () {drawable drawable = Loadimagefromurl (IMAGEURL);
Store the resulting picture in the cache Mimagecache.put (IMAGEURL, New softreference<drawable> (drawable));
Message message = Handler.obtainmessage (0, drawable);
Handler.sendmessage (message);
};
}.start ();
If the cache does not exist, will be downloaded from the Internet after the completion of this place null; return null;
//define a callback interface public interface Imagecallback {void Imageload (drawable drawable); ///Get Picture Drawable object from Internet via URL protected drawable loadimagefromurl (String imageUrl) {try {return drawab
Le.createfromstream (New URL (IMAGEURL). OpenStream (), "Debug");
catch (Exception e) {//Todo:handle Exception throw new RuntimeException (e);
}
}
}
Weak reference (WeakReference)
Objects that have only weak references have a more ephemeral lifecycle. When the garbage collector thread scans the area of memory it governs, it reclaims 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.
weakreference<user> sr = new Weakreference<user> (new User ());
Handler weak references to prevent memory leaks
Package rxnet.zyj.com.myapplication;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import java.lang.ref.WeakReference;
public class Mainactivity extends Appcompatactivity {private Handler Handler;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Handler = new MyHandler (this);
New Thread (New Runnable () {@Override public void run () {handler.sendemptymessage (0);
}). Start ();
private static class MyHandler extends Handler {weakreference<mainactivity> weakreference;
Public MyHandler (mainactivity activity) {weakreference = new weakreference<mainactivity> (activity);
@Override public void Handlemessage (msg) {super.handlemessage); if (weakreference.get ()!= null) {
Update Android UI}}}