Android Memory , Where is all My RAM

Post on 27-Jan-2017

532 views 1 download

Transcript of Android Memory , Where is all My RAM

Rights reserved

Android Memory"Where is all my RAM"

Rights reserved

Deep Dive Into State Restoration

Rights reserved

+Yossi Elkrief @elkriefy

MaTriXy

Android Group leader Tikal

Proud Father Android developer since 2008 GDG Beer Sheva co-founder & leader Android Mentor @ Google Campus Android Lecturer & speaker LFC fan Androids collector

Rights reserved

Android Memory

Rights reserved

Android MemoryAndroid Memory

• Android does not offer swap space for memory.

• Android’s VM performs routine GC.

• Don’t ignore when and where app allocates and releases memory.

• The only way is analyze app’s memory usage with tools and proper care.

Rights reserved

• The Java heap• The native heap • Android shared memory - ashmem.

Android Memory Regions

Rights reserved

Android Memory Regions• The Java heap per-application limited size by the device

manufacturer. Memory is garbage-collected.

• The native heap used by the C++ new operator.The app is limited only by the physical memory available on the device. There is no garbage collection.

• Android shared memory - ashmem. Android can “unpin” the memory rather than freeing it. This is a lazy free; the memory is freed only if the system actually needs more memory. When Android “pins” the memory back, old data will still be there if it hasn't been freed.

Rights reserved

• android:largeHeap • All processes in application.

• Shared user ID - all must have same Flag.

• Better focus on reducing overall memory usage.

• Does not guarantee a fixed increase in available memory.

Increase Heap size

Rights reserved

Viewing Heap Updates

http://static.tumblr.com/52679116680c197db232c3116ce98537/y07rdrp/1XJmt370e/tumblr_static_demotimeheader2.png

Rights reserved

How Android Manages Memory

• Sharing Memory

• App is Forked from Zygote.

• Zygote starts on system boot , loads

common framework code and resources.

Rights reserved

How Android Manages Memory

• Static data is mmapped into a process. Allows page out when needed.

• Android shares dynamic RAM across

processes using explicitly allocated shared

memory regions.

Rights reserved

How Android Manages Memory

• Restricting App Memory

• Hard limit heap size for each app

• Heap size limit varies between devices

• ActivityManager.getMemoryClass ()

Rights reserved

How Android Manages Memory

• Switching Apps

• Android keeps processes cached

• Least-recently used (LRU) cache

Rights reserved

Rights reserved

Memory Leak

• Memory leak is when code has a reference to an object that is no longer needed, preventing the VM to perform the garbage collection for that reference.

• Degradation in performance as the memory consumption increases.

Rights reserved

Memory Leak

• Application tries to exceed the available memory,

• We get Out of Memory.

Rights reserved

Viewing Overall Memory Allocations

• Private RAM

• Clean

• Dirty

• Proportional Set Size (PSS)

adb shell dumpsys meminfo <package_name>

Rights reserved

Private (Clean and Dirty) RAM• Memory that is being used by only your process.

• RAM that the system can reclaim when your app’s process is destroyed.

• Most important portion is “private dirty” RAM - the most expensive.

• Used by only your process and its contents exist only in RAM so can’t be paged to storage.

• Dalvik and native allocations will be private dirty RAM

• Dalvik and native allocations you share with the Zygote process are shared dirty RAM.

Rights reserved

Proportional Set Size (PSS)• Measurement of app’s RAM usage that takes into account sharing pages across

processes.

• RAM pages that are unique to process directly contribute to its PSS value.

• Shared Pages contribute to the PSS value only in proportion to the amount of sharing.

• For example, a page that is shared between two processes will contribute half of its size to the PSS of each process.

• PSS from all processes actual memory usage in device.

• Good Comparison against the RAM use of other processes.

Rights reserved

GC Log Messages

• logcat prints a message every GC (Only on Dalvik):

• ART GC Log message.

• Explicit GC

• GC pause >5ms

• GC duration > 100ms

Rights reserved

Interpreting Log Messages

• D/dalvikvm: <GC_Reason> <Amount_freed>,

<Heap_stats>, <External_memory_stats>,

<Pause_time>

Rights reserved

Interpreting Log Messages

• I/art: <GC_Reason> <GC_Name> <Objects_freed>(<Size_freed>) AllocSpace Objects, <Large_objects_freed>(<Large_object_size_freed>) <Heap_stats> LOS objects, <Pause_time(s)>

Rights reserved

Tracking Allocations• Narrowing down memory issues.

• Better understanding memory-hogging objects allocations.

• Useful to analyze critical code paths.

• For example - flinging a list in your app

• Viewing all the allocations that need to be done for that behaviour.

• What thread they are on.

• Where they came from.

Rights reserved

Tracking Allocations Demo

http://upload.wikimedia.org/wikipedia/commons/8/85/Flickr_-_The_U.S._Army_-_Working_dog_demo.jpg

Rights reserved

References• SoftReference

• WeakReference

• PhantomReference.

• "Weakness" less restrictions on the garbage

collector as to when it is allowed to actually

Rights reserved

References

• SoftReference

• Object is not strongly reachable.

• There is at least one path from the root set to

the object that does traverse a

java.lang.ref.SoftReference.

Rights reserved

References• WeakReference

• Object is neither strongly nor softly

reachable.

• There is at least one path from the root set to

the object that does traverse a

java.lang.ref.WeakReference.

Rights reserved

References• PhantomReference.

• Object is neither strongly, softly, nor weakly

reachable.

• The object is referenced by a

java.lang.ref.PhantomReference instance.

• The object has already been finalized.

Rights reserved

Eclipse Memory Analyser ToolMAT

Rights reserved

Process Stats: Understanding How Your App Uses RAM

Rights reserved

Process Stats

• Available since KitKat

• Settings > Developer options > Process Stats.

• Usage is quite simple.

• Try it out now

Rights reserved

Memory leaks Examples

Rights reserved

• Anonymous Inner Class - keeps a reference to instance of parent.

• Activity leak

• Threads leak

• Handler leak

Rights reserved

Hunting memory leaks• Get an OutOfMemoryError (OOM) crashe/s .

• Attempt to reproduce the problem. You need to figure out what navigation sequence triggers the leak, possibly by brute force.

• Dump the heap when the OOM occurs.

• Poke around the heap dump and find an object that should have been garbage collected.

• Compute the shortest strong reference path from that object to the GC roots.

• Figure out which reference in the path should not exist, and fix the memory leak.

Rights reservedhttp://cdn.meme.am/instances/500x/58311156.jpg

Rights reservedhttp://www.gxsblogs.com/wp-content/uploads/Trash-Big-Data.png

Rights reserved

The story ofLeakCanary

https://corner.squareup.com/2015/05/leak-canary.html

Rights reserved

LeakCanary:Detect all memory leaks!

Rights reserved

LeakCanary

• A memory leak detection library for Android and Java.

• Built by Square

• Easy to integrate

• Full open source project - on Github

• https://github.com/square/leakcanary

Rights reserved

Tips to Go

• Avoid Memory Churn.

• Avoid Objects allocation inside onDraw().

• Keep an eye on your References.

• Avoid Soft References for caching

Rights reserved

• Avoid using non-static inner classes in an activity if

instances of the inner class could outlive the activity's

lifecycle.

• Avoid passing anonymous inner class objects to static / singleton classes which keep a strong reference to it.

• Don’t hold references to activities whenever possible.

Tips to Go

Rights reserved

• Use objects pool - created once and reused.

• Blank activity with very little memory consumption, transition to it and force a GC.

• Use Heap dump.

• Use Allocation Tracker.

before and after the transition.

Tips to Go

Rights reserved

• GC : Don’t call me…

http://memecrunch.com/meme/1C7NB/i-m-not-saying-don-t-call-me/image.jpg

Till next time, Yossi is satisfied

Rights reserved

Thank you!

Rights reserved

Resources• developer.android.com • Multitasking-android-way• process stats

Roboto font.

Inside Techsmith images • Dennis Cornwell Keynote animation and style • Cyril Mottier

https://github.com/MaTriXy/RecyclerviewDemos • Yossi Elkrief