Memory Leaks in Android Applications

36
Memory Leaks in Android Apps

Transcript of Memory Leaks in Android Applications

Page 1: Memory Leaks in Android Applications

Memory Leaks in Android Apps

Page 2: Memory Leaks in Android Applications

Memory Management in Java

→ Objects need not to be destroyed manually .

→ Unused objects are discarded by the Garbage Collector (GC) of JVM

→ GC uses the concept of dominator tree to decide the objects to be destroyed .

{ Read about Dominator Tree , pretty interesting stuff }

Page 3: Memory Leaks in Android Applications

Types Of Garbage Collectors

● Tracing garbage collectorsa. Stop-the-world garbage collectors completely halt execution of the program to run a collection cycleb. Incremental and concurrent garbage collectors are designed to reduce this disruption by interleaving their work

with activity from the main program. Incremental garbage collectors perform the garbage collection cycle in discrete phases, with program execution permitted between each phase (and sometimes during some phases).

c. Concurrent garbage collectors do not stop program execution at all, except perhaps briefly when the program's execution stack is scanned.

● Reference counting

Page 4: Memory Leaks in Android Applications

Types Of Garbage Collectors in Android Pre-Gingerbread GC:

– Stop-the-world– Full heap collection– Pause times often > 100ms

Gingerbread and beyond: – Concurrent (mostly)

– Partial collections– Pause times usually < 5ms.

ART and beyond: – Concurrent (mostly)– Offloads some of the work of garbage collection to application itself.

Only one pause time.– packard pre-cleaning

{ READ ABOUT GC’s }

Page 5: Memory Leaks in Android Applications

Types of References

→ Strong Reference

→ Soft Reference

→ Weak Reference

→ Phantom reference

Page 6: Memory Leaks in Android Applications

The keyword “Static”

→ Life time of a Static variable is almost same as the life time of Process.

public class MainActivity extends Activity {

static Dialog dialog = null;

public onCreate(Bundle bundle) {….

dialog = new Dialog(this);

}

…..

}

Page 7: Memory Leaks in Android Applications

Static Inner Class Vs Non_static Nested classes:

→ A non-static nested class (or 'inner class') has full access to the members of the class within which it is nested.

→ A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

public class MainActivity extends Activity {

static Leaky leak = null;

class Leaky { void doSomething() { System.out.println("Wheee!!!"); }

}

Page 8: Memory Leaks in Android Applications

Memory Leak→ Memory Leak in Java is a situation where some objects are not used by the application any more but GC fails to recognize them as unused objects

→ Remember that an object is considered unused only if it is no longer referenced

by any other object.

⇒ This gives an insight into memory leak. If an object holds a reference to an

object which is no longer used and supposed to be destroyed , then the referred

object is considered to be usable by the Garbage collector and not collected

Page 9: Memory Leaks in Android Applications

Memory Leaks in Android

→ Since Mobile devices have a limited amount of memory , Memory Leaks turn to be fatal in Android Devices .

→ Memory Leaks give errors called “Out Of Memory Error” (fondly called as OOM)

→ An OOM occurs when the heap size of the application exhausts or the jvm is unable to find a large enough block of memory needed (See Compaction Policy)

→ Both the cases are caused by the application eating out a lot of memory which is mostly due to memory leaks {If not you use large number of bitmaps}

Page 10: Memory Leaks in Android Applications

Example of Memory Leak

→ Suppose an Activity uses a handler to make and process a network call.

→ Handler runs on a separate thread . If the handler is a non static inner class of the activity , it holds a reference to the activity that created it .

→ In case the activity is to be destroyed due to user navigation (after the initiation of network call but before the response) , the activity is referenced by the handler and so it cannot be destroyed.

Object supposed to be destroyed not garbage collected

===> MEMORY LEAK

Page 11: Memory Leaks in Android Applications

Detecting Cause for OOM → Unlike other exceptions , the stack traces obtained from OOM errors are fairly useless.

→ This is because the app crashes at the moment free heap space exhausts and the line of code executed at that point of time fails and throws error which may not be the root cause for the error

{In our case , Most of the stack traces caught at OOM were like parsing the response obtained , inflating a layout which are pretty less memory consuming operations }

Page 12: Memory Leaks in Android Applications

Memory status at a typical crash

Page 13: Memory Leaks in Android Applications

Memory Issues in our app

→ There is no systematic procedure to detect memory leaks .

→ The only way to detect and fix OOM errors is to randomly try crashing the app and analyze the memory snapshot at the time of crash .

→ Analyzing the memory ==> Looking for peculiar or unnecessary class and activity instances , memory consuming objects and other libraries.

→ We tried to crash the app in various user flows and present some user flow crash and insights .

Page 14: Memory Leaks in Android Applications

Analysing Heap Dump {Memory} using Eclipse MAT

→ MAT ===> Memory Analysing Tool by Eclipse

→ Heap dump can be taken at any point of time from Android Studio {in memory tab} and it has to be converted to MAT compatible format using hprof-conf command in platform-tools of Studio.

→ MAT has many features such as

1. Heap size , objects of each class with many filters

2. Leak Suspects pie chart with probable leaks in the app

3. Dominator tree ,Shallow and Retained heaps for each object

Page 15: Memory Leaks in Android Applications
Page 16: Memory Leaks in Android Applications
Page 17: Memory Leaks in Android Applications
Page 18: Memory Leaks in Android Applications

Example

Page 19: Memory Leaks in Android Applications

Leak Suspect Report

Page 20: Memory Leaks in Android Applications

Object instances of each class

Page 21: Memory Leaks in Android Applications

● In the following slides , we see the user flows leading to crashes most of the times in the current build AND ALSO compare the hotfix build , current build with the issues fixed.

● We performed similar user flows in both the builds on a low end device Samsung Duos (GT S7392)

NOTE : The memory fixes for each crash may be interdependent . Fix shown for each crash is major cause for that, but it may include leaks which cause other crashes as well.

Page 22: Memory Leaks in Android Applications

Flow 1 - ***

→ Analysing the heap dump {Memory Snapshot } at crash time , we observed that the external library “ViewFlow” used for the horizontal gallery view (in detail page ) consumed a large amount of memory .

Fix : The horizontal gallery swipe is implemented by Android framework’s

ViewPager which significantly reduced the memory usage .

Page 23: Memory Leaks in Android Applications

version (X) version (X+1)With Memory Leak After Fixing the Leak

Memory Used 120.7 Mb 47.2 Mb

Page 24: Memory Leaks in Android Applications

Flow 2 - ***

→ The above flow sometimes causes the app crash

→ From the heap dump , we found that the LRUCache of picasso library (Used for image loading) has 2 instances accounting to a whooping 30% of the total heap size .

Fix : LRUCache instance is made singleton and this reduced the memory usage of

the picasso library by 50 %

Page 25: Memory Leaks in Android Applications

v (X) v (X+1)

Memory Used 42 Mb 37.8 Mb

LRU Cache Objects 2 1

* LRU Cache objects are costly as each object consumes 15% of the heap space for caching images.

Page 26: Memory Leaks in Android Applications

Flow 3

→ The above user flow is also observed to cause crash few times .

→ We found that the Activity “x” has two instances at times whereas we strictly limit its instance to One and kill the existing instance if a new one has to be created .

Cause : Context Leak from some other service

Fix : All the unnecessary activity context passing is replaced by passing

Application Context

Page 27: Memory Leaks in Android Applications

v (X) v (X+1)

Memory Used 42.6 Mb 30.2 Mb

x Class Objs. 2 1

NOTE : Activity Leak is fatal as it leaks entire resources associated with it.

Page 28: Memory Leaks in Android Applications

LIVE DEMO

Page 29: Memory Leaks in Android Applications

Flow 4

Cause : Android Framework is holding reference to our MapFragmentActivity even

after it is destroyed and not letting it garbage collected.

{ Framework Level issue }

Fix : Make our MapFragmentActivity as light as possible.

Page 30: Memory Leaks in Android Applications

v (X) v (X+1)

Memory Used 56.8 Mb 40.3 Mb

Page 31: Memory Leaks in Android Applications

Optimizing Images➔ Use BitMap Factory to load only the image according to screen resolution.➔ Use low resolution for low end devices. This saves bandwidth also.➔ Use RGB_565 instead of ARGB_8888 on low end devices.

Page 32: Memory Leaks in Android Applications

Leak Canary

→ Library used to detect memory leaks.

→ Catches OOO, dumps heap immediately, and uploads them.

→ Analyses the dump in background and notifies using notifications.

→ Can’t be used in production since the size of dump is huge.

→ Once the QA notifies that there is a leak, analyse the dump using MAT.

Page 33: Memory Leaks in Android Applications

Best Practices recap

● Never create a Context variable. ○ Use Commonfloor.getContext() for application context○ Use this for Activity context.

● Don’t use static variables.● Prefer static nested classes over non-static inner classes.● Make the object as light as possible if a framework issue exists.● Use LeakCanary early in the QA cycle to detect potential leaks.● Compare the heap usage with each successive release.

Page 34: Memory Leaks in Android Applications

References

1. Memory Management in Android Apps - Google I/O 2011

2. http://wiki.eclipse.org/index.php/MemoryAnalyzer

Page 35: Memory Leaks in Android Applications

Questions / Suggestions

Page 36: Memory Leaks in Android Applications

THANK YOU FOR YOUR PATIENCE :)