Android uses LeakCanary to detect memory leaks

Android uses LeakCanary to detect memory leaks

Four types of Java references

In Java, there are four different reference types: strong reference, soft reference, weak reference and phantom reference.

(1) Strong Reference is the most common type of reference. It refers to a reference relationship that is commonly found in a program. As long as a strong reference exists, the garbage collector will not recycle the referenced object. For example:

 Object obj = new Object();

In the above code, obj is a strong reference pointing to a newly created Object object. As long as obj exists, the garbage collector will not reclaim the object.

(2) Soft reference is a reference type that is weaker than strong reference. Before the system is about to overflow memory, the object pointed to by soft reference will be recycled as much as possible. For example:

 SoftReference<Object> softRef = new SoftReference<>(new Object());

In the above code, softRef is a soft reference pointing to a newly created Object object. When the system is low on memory, the garbage collector may reclaim the object.

(3) Weak Reference is a reference type that is weaker than Soft Reference. When the garbage collector is working, as long as a weak reference is found, the referenced object will be recycled regardless of whether the system memory is sufficient. For example:

 WeakReference<Object> weakRef = new WeakReference<>(new Object());

In the above code, weakRef is a weak reference pointing to a newly created Object object. When the garbage collector finds that the object has only a weak reference, it will recycle it.

(4) Phantom Reference is the weakest reference type, which has almost no reference function. Phantom Reference is mainly used to track the state of objects being garbage collected. It is impossible to obtain the instance of the object through Phantom Reference. For example:

 ReferenceQueue<Object> queue = new ReferenceQueue<>(); PhantomReference<Object> phantomRef = new PhantomReference<>(new Object(), queue);

In the above code, phantomRef is a virtual reference pointing to a newly created Object object. When the garbage collector is ready to recycle the object, it will add the virtual reference to the queue.

Use scenarios:

  • Strong Reference: Strong reference is the most common type of reference. It refers to the reference relationship that is commonly found in the program. As long as the strong reference exists, the garbage collector will not recycle the referenced object. Strong reference is suitable for situations where the object must always exist, but it is also easy to cause memory leaks.
  • Soft Reference: Soft reference is a reference type that is weaker than strong reference. When memory is insufficient, the garbage collector will try to recycle the object pointed to by the soft reference. Soft reference is suitable for cache scenarios. When memory is insufficient, the cache can be released to avoid OutOfMemoryError.
  • Weak Reference: A weak reference is a reference type that is weaker than a soft reference, and its life cycle is shorter. When the garbage collector performs garbage collection, the object pointed to by the weak reference will be recycled regardless of whether there is sufficient memory. Weak references are suitable for temporary references, such as temporary objects in the cache.
  • Phantom Reference: Phantom reference is the weakest reference type. Its existence is almost meaningless and is mainly used to track the state of objects being garbage collected. Phantom reference must be used together with ReferenceQueue. When the garbage collector is ready to recycle an object, if it is found that it has a phantom reference, it will add the phantom reference to the reference queue. Phantom reference is suitable for some scenarios that need to perform specific operations when the object is recycled.

Introduction to LeakCanary

LeakCanary is an open source library for detecting memory leaks in Android applications. It can help developers find and solve memory leaks in a timely manner during application operation, and improve application stability and performance.

Using LeakCanary is very simple. You only need to add the dependency to the build.gradle file of the application and initialize it in the Application class. LeakCanary will automatically monitor the memory leaks of the application and send a notification when a memory leak is detected.

LeakCanary works by monitoring the object reference relationships in the application. When an object is created, LeakCanary will track its reference chain. If it finds that the object is not released correctly, it will trigger the detection and reporting of memory leaks. LeakCanary will generate a detailed memory leak report, including the reference chain of the leaking object and related context information, to help developers quickly locate and fix memory leaks. Its workflow is as follows:

  • Monitoring: LeakCanary monitors the memory allocation and release of the application by adding a monitor to the application. It periodically checks for memory leaks in the main thread of the application.
  • Analysis: When LeakCanary detects a memory leak, it collects relevant memory information and generates a memory leak report. The report contains the reference chain of the leaking object, that is, the reference relationship between the objects that caused the memory leak.
  • Notification: LeakCanary will send memory leak reports to developers, usually through the notification bar. Developers can click on the notification to view the report to understand the specific situation of the memory leak.
  • Debugging: Developers can locate and fix memory leaks based on the reference chain information in the report. LeakCanary provides some tools and suggestions to help developers debug and fix.

LeakCanary helps developers to promptly detect and resolve memory leaks in Android apps through monitoring, analysis and notifications, which helps improve the performance and stability of apps.

LeakCanary usage

(1) Add the LeakCanary dependency to the project's build.gradle file:

 dependencies { debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.12' releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:2.12' }

(2) Initialize LeakCanary in the onCreate() method of the Application class:

 public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { return; } LeakCanary.install(this); } }

(3) Run the app and perform some operations in the app so that LeakCanary can detect memory leaks.

(4) When LeakCanary detects a memory leak, it displays a notification in the notification bar. Click the notification to view detailed memory leak information, including the reference chain of the leaking object and the location where the leak occurred.

By using LeakCanary, developers can promptly detect and resolve memory leaks in their applications, improving application performance and stability.

<<:  Exploration and practice of intelligent film performance optimization

>>:  Compose-Multiplatform Practice on Android and iOS

Recommend

This sentence you have been told since childhood may be destroying your health

Our parents have always emphasized this to us sin...

How to find cooperation channels with anchors who sell products?

How to find cooperation channels with anchors who...

How to reduce the size of Android apps

【51CTO.com Quick Translation】I wonder if you have...

Mental illness isn't just caused by brain chemicals

Leviathan Press: Generally speaking, people who p...

Tips for placing advertisements in the gaming industry’s circle of friends!

This article will explore the placement technique...

3 ways to promote your product, one picture is enough!

For a large, mature company, promoting a new prod...