How leakcannry works

1. Concept

1.1 The meaning and function of ReferenceQueue
Usually we translate ReferenceQueue as a reference queue, in other words, it is a queue that stores references, and what is saved is the Reference object. Its function is that when the object referenced by the Reference object is recycled by GC, the Reference object will be added to the end of the queue in the reference queue (ReferenceQueue).

1.2 What if it is determined that the object referenced by Reference has been recycled?
1.2.1 If the Reference taken out from the reference list ReferenceQueue is not empty, it means that the object has been recycled.
1.2.2 If it is empty, it means it has been leaked.

2. How does leakcannry detect leaks?

  1. When installing, the activityLifecycleCallbacks monitor will be registered to monitor the execution of onDestry (equivalent to the first GC).
  2. Create a reWacher object. Two lists will be maintained in the object, watchedReferences (observation list) and retainedReferences (suspect list).
  3. When the watch method (called when onDestry is executed) is executed,
    3.1. will first clear the watch list and suspicion list,
    3.2. Then create a WeakReference and generate a unique key to associate the WeakReference with the reference queue.
    3.3 Add the current WeakReference to the watch list.
    4. After waiting for 5 seconds, if the object is recycled, there will be data in the reference queue, then the WeakReference in the reference queue will be taken out and compared with the WeakReference in the observation list (through the previously generated key). If they are consistent, the observation will be WeakReference removed from the list. If there is data in the watch list, indicating that there may be a leak, then move the WeakReference from the watch list to the suspect list.
    5. Detect memory leaks in the worker thread.
    If WeakReference is added to the suspicion list, GC will be actively executed again. If it is recycled, it will end. Otherwise, the heap memory will be dumped.
    Insert image description here

рекомендация

отblog.csdn.net/L779442863/article/details/125677663