Memory leaks in Android — identify, treat and avoid

print
https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8

https://android.jlelse.eu/memory-leak-patterns-in-android-4741a7fcb570

https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html

 

https://github.com/square/leakcanary

 

What is a memory leak?

Every app needs memory as a resource to do its work. To make sure each app in Android has enough memory, Android system needs to manage memory allocation efficiently. Android runtime triggers Garbage Collection (GC) when memory runs short. The purpose of GC is to reclaim memory by cleaning up objects that are no longer useful. It achieves it in three steps.

  1. Traverses all object references in memory from GC roots and marks active objects which has references from GC roots.
  2. All objects which are not marked (garbages) are wiped from memory.
  3. Rearrange live objects
Marking live objects from GC roots [2]

In short, everything serving the user should be kept in memory and everything else are wiped out from memory to free up resources.

java.lang.OutOfMemoryError
        at android.graphics.Bitmap.nativeCreate(Bitmap.java:-2)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:689)
        at com.squareup.ui.SignView.createSignatureBitmap(SignView.java:121)

Nobody likes OutOfMemoryError crashes

In Square Register, we draw the customer’s signature on a bitmap cache. This bitmap is the size of the device’s screen, and we had a significant number of out of memory (OOM) crashes when creating it.

https://medium.com/square-corner-blog/leakcanary-detect-all-memory-leaks-875ff8360745

LeakCanary

A memory leak detection library for Android and Java.

“A small leak will sink a great ship.” – Benjamin Franklin

Handling memory leaks in Java programs

 

https://www.ibm.com/developerworks/java/library/j-leaks/

https://developer.android.com/studio/profile/investigate-ram.html

Investigating Your RAM Usage

When you develop Android apps, always pay attention to how much random-access memory (RAM) your app uses. Although the Dalvik and ART runtimes perform routine garbage collection (GC), you still need to understand when and where your app allocates and releases memory. To provide a stable user experience where the Android operating system can quickly switch between apps, make sure that your app does not unnecessarily consume memory when the user is not interacting with it.

Even if you follow all the best practices for Managing Your App Memory during development, you might still leak objects or introduce other memory bugs. The only way to be certain your app is using as little memory as possible is to analyze your app’s memory usage with the tools described here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.