First look at several Java reference:
Starting with JDK 1.2, references are divided into strong references, soft references, if references, and virtual references, where soft references, references, and virtual references are associated with Referencequeue.
In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.
1, strong references (strong Reference, no specific classes to identify strong references, normal use of object references are strong references, implemented by VMS)
Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it.
When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
2, soft reference (SoftReference)
If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed.
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), if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add this soft reference to the reference queue associated with it.
3,Weak references (WeakReference)
The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle.
As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is 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 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 adds the weak reference to the reference queue associated with it.
4, virtual reference (phantomreference)
"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.
Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue) .
When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory.
Referencequeue queue = new Referencequeue (); Phantomreference PR = new Phantomreference (object, queue);
The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program discovers that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.
5,referencequeue is a message passing between the JVM GC and the upper reference object management, and the queued operation of the soft reference, the reference, etc. has the GC direct operation of the VM
Leakcanary in therefwatcher is monitored by reference and its queue:
There are two very heavy structures: Retainedkeys and queue,
retainedkeys represents objects that are not collected by GC,  
And if the reference in the queue is a GC object, the two structures can be used to monitor whether the object is recycled;
The Retainedkeys stores the unique key that refwatcher generates for each monitored object;
At the same time, if the reference (keyedweakreference) of each monitored object is associated with its corresponding key and queue, if the object is recycled, then its corresponding reference will be queued to the queue;
Removeweaklyreachablereferences (.. What is done is to delete the existing and the referenced key in the queue from the Retainedkeys.
private final Set<String> retainedKeys; private final referencequeue<object> queue;/** * watches the provided References and checks if it can be gced. this method is non blocking, * the check is done on the {@link executor} this {@link RefWatcher} has been constructed with. * * @param referencename an logical identifier for the watched object. */ public void watch (Object Watchedreference, string referencename) { checknotnull (WatchedReference, "Watchedreference"); checknotnull (referencename, "referencename"); if (DebuggeRcontrol.isdebuggerattached ()) { return; } final long watchstartnanotime = system.nanotime (); string key = uuid.randomuuid (). toString (); retainedkeys.add ( Key); final keyedweakreference reference = new keyedweakreference (Watchedreference, key, referencename, queue); watchexecutor.execute (new runnable () { @ Override public void run () { ensuregone ( Reference, watchstartnanotime); } }); }void ensuregone (keyedweakreference reference, long watchstartnanotime) { long gcsTartnanotime = system.nanotime (); long watchdurationms = Nanoseconds.tomillis (gcstartnanotime - watchstartnanotime); Removeweaklyreachablereferences (); if (Gone (reference) | | debuggercontrol.isdebuggerattached ()) { return; &NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;GCTRIGGER.RUNGC (); removeweaklyreachablereferences (); if (!gone (reference)) { long Startdumpheap = system.nanotime (); long gcdurationms = nanoseconds.tomillis (startdumpheap - gcstartnanotime); file heapdumpfile = heapdumper.dumpheap (); if (heapDumpFile == heapdumper.no_dump) { // could not dump the heap, abort. return; } Long heapdumpdurationms = nanoseconds.tomillis (System.nanotime () - startDumpHeap); heapdumplistener.analyze ( new heapdump (heapdumpfile, reference.key, reference.name, excludedrefs, watchdurationms, GCDURATIONMS,&NBSP;HEAPDUMPDURATIONMS)); } }private boolean gone ( Keyedweakreference reference) { return !retainedkeys.contains ( Reference.key); } private void removeweaklyreachablereferences () { // weakreferences are enqueued as soon as the object to which they Point to becomes weakly // reachable. this is before finalization or garbage collection has actually happened. KeyedWeakReference ref; while (ref = ( keyedweakreference) queue.poll () != null) { Retainedkeys.remove (Ref.key); } }
When do I use Refwatcher for monitoring?
For Android, to monitor activity, you need to monitor it when it executes destroy:
By registering Activitylifecyclecallback with application, you start listening to activity objects in onactivitydestroyed activity. Because the activity should be recycled, if there is a memory leak, it can not be found;
Refwatcher checks whether the object is recycled is performed in a Executor, Android monitoring provides androidwatchexecutor, it executes on the main thread, but has a delay time (default milisecs) , because for application, performing destroy activity simply recycles the necessary resources, and the activity objects are not necessarily immediately recycled by GC.
Androidwatchexecutor:
private void Executedelayedafteridleunsafe (final Runnable Runnable) {//This needs to is called from the main thread. Looper.myqueue (). Addidlehandler (New Messagequeue.idlehandler () {@Override public boolean queueidle () {BAC Kgroundhandler.postdelayed (runnable, Delay_millis); return false; } }); }
Activityrefwatcher:
Package com.squareup.leakcanary;import android.annotation.targetapi;import android.app.activity ;import android.app.application;import android.os.bundle;import static Android.os.build.version.sdk_int;import static android.os.build.version_codes. ice_cream_sandwich;import static com.squareup.leakcanary.preconditions.checknotnull; @TargetApi (ICE_ Cream_sandwich) public final class activityrefwatcher { public static void installonicsplus (Application application, refwatcher refwatcher) { if (Sdk_int < ice_cream_sandwich) { // If you need to support Android < ICS, override OnDestroy () in your base activity. return; } activityrefwatcher Activityrefwatcher = new activityrefwatcher (Application, refwatcher); activityrefwatcher.watchactivities (); } private final Application.activitylifecyclecallbacks lifecyclecallbacks = new application.activitylifecyclecallbacks () { @Override public void onactivitycreated (Activity activity, bundle savedinstancestate) { } @ Override public void onactivitystarted (activity activity) { } @Override public void Onactivityresumed (activity activity) { } @OverridE public void onactivitypaused (activity activity) { } @Override public void onactivitystopped (activity activity) { } @Override public void onactivitysaveinstancestate (Activity activity, bundle outstate) { } @Override public void onactivitydestroyed (activity Activity) { ActivityRefWatcher.this.onActivityDestroyed (activity); } }; private final Application application; Private final refwatcher refwatcher; /** * constructs an {@link activityrefwatcher} that will make sure the activities are not leaking * after they have been destroyed. */ public activityrefwatcher ( Application application, final refwatcher refwatcher) { This.application = checknotnull (application, "Application"); This.refwatcher = checknotnull (refwatcher, "Refwatcher"); } void Onactivitydestroyed (activity activity) { refwatcher.watch (Activity); } public void watchactivities () { // Make Sure you don ' t get installed twice. stopwatchingactivities (); application.registeractIvitylifecyclecallbacks (lifecyclecallbacks); } public void Stopwatchingactivities () { application.unregisteractivitylifecyclecallbacks ( lifecyclecallbacks); }}
If a leak occurs, Refwatcher executes a dump, generates a dump file, and then finds a reference path to the compromised object by an analysis tool such as mat or haha.
Reference: http://blog.csdn.net/lyfi01/article/details/6415726, http://hongjiang.info/java-referencequeue/
Android Memory leak Detection Tool leakcanary monitoring principle