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.
The simplest place to begin investigating your app’s memory usage is in the runtime log messages. Sometimes when a GC occurs, you can view the message in logcat.
In Dalvik (but not ART), every GC prints the following information to logcat:
D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>
Example:
D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms
GC_CONCURRENT
GC_FOR_MALLOC
GC_HPROF_DUMP_HEAP
GC_EXPLICIT
gc()
(which you
should avoid calling and instead trust the GC to run when needed).GC_EXTERNAL_ALLOC
While these log messages accumulate, look out for increases in the heap stats (the
3571K/9991K
value in the above example). If this value continues to increase, you might
have a memory leak.
Unlike Dalvik, ART doesn't log messages for GCs that were not explicitly requested. GCs are only printed when they are they are deemed slow. More precisely, if the GC pause exceeds 5ms or the GC duration exceeds 100ms. If the app is not in a pause perceptible process state, then none of its GCs are deemed slow. Explicit GCs are always logged.
ART includes the following information in its garbage collection 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)>
Example:
I/art : Explicit concurrent mark sweep GC freed 104710(7MB) AllocSpace objects, 21(416KB) LOS objects, 33% free, 25MB/38MB, paused 1.230ms total 67.216ms
Concurrent
Alloc
Explicit
gc()
or
gc()
. Like Dalvik, in ART the
best practice is that you trust the GC and avoid requesting explicit GCs, if possible.
Explicit GCs are discouraged because they block the allocating thread and unnecessarily waste CPU
cycles. Explicit GCs could also cause jank (stuttering, juddering, or halting in the app) if they
cause other threads to get preempted.NativeAlloc
CollectorTransition
HomogeneousSpaceCompact
DisableMovingGc
HeapTrim
Concurrent mark sweep (CMS)
Concurrent partial mark sweep
Concurrent sticky mark sweep
Marksweep + semispace
If you are seeing a large amount of GCs in logcat, look for increases in the heap stats (the
25MB/38MB
value in the above example). If this value continues to increase and doesn't
ever seem to get smaller, you could have a memory leak. Alternatively, if you are seeing GC which
are for the reason "Alloc", then you are already operating near your heap capacity and can expect
OOM exceptions in the near future.
Figure 1. Android Monitor and three of its monitors: Memory, CPU, and GPU. In Android Studio, enlarge the Android Monitor panel vertically to see the Network monitor.
A heap dump is a snapshot of all of the objects in your app's heap. The heap dump is stored in a binary format called HPROF that you can upload into an analytics tool such as jhat. Your app's heap dump contains information about the overall state of your app's heap so that you can track down problems you might have identified while viewing heap updates.
Android Studio creates a heap snapshot file with the filename
application-id_yyyy.mm.dd_hh.mm.hprof
, opens the
file in Android Studio,
and adds the file to the Heap Snapshot list in the Captures tab.
Note: If you need to be more precise about when the dump is created, you
can create a heap dump at the critical point in your app code by calling
dumpHprofData()
.
Use Android Monitor to view real-time updates to your app's heap while you interact with your app. The real-time updates provide information about how much memory is allocated for different app operations. You can use this information to decide whether any operations use too much memory and need to be adjusted to use less.
Continue to interact with your app and initiate GCs. Watch your heap allocation update with each GC. Identify which actions in your app cause too much allocation and where you might reduce allocations and release resources.
The heap dump is provided in a format that is similar, but not identical, to the one from the Java HPROF tool. The major difference in an Android heap dump is that there are a large number of allocations in the Zygote process. Because the Zygote allocations are shared across all app processes, they don’t matter very much to your own heap analysis.
To analyze the heap dump, you can use a standard tool like
jhat.
To use jhat, you need to convert the HPROF file from Android format to the Java SE HPROF format.
To convert to Java SE HPROF format, use the hprof-conv
tool provided in the
ANDROID_SDK/platform-tools/
directory. Run the hprof-conv
command with two arguments: the original HPROF file and the location to write the converted HPROF
file. For example:
hprof-conv heap-original.hprof heap-converted.hprof
You can load the converted file into a heap analysis tool that understands the Java SE HPROF format. During the analysis, look for memory leaks caused by any of the following:
Activity
, Context
, View
,
Drawable
, and other objects that might hold a
reference to the Activity
or Context
container.Runnable
, that can hold
an Activity
instance.Tracking memory allocations can give you a better understanding of where your memory-hogging objects are allocated. You can use Allocation Tracker to look at specific memory uses and to analyze critical code paths in an app such as scrolling.
For example, you might use Allocation tracker to track allocations while you fling a list in your app. The tracking lets you see all of the memory allocations required for flinging the list, what thread the memory allocations are on, and where the memory allocations come from. This kind of information can help you streamline the execution paths to reduce the work they do, which improves the overall operation of the app and its user interface.
Although it is not necessary or even possible to remove all memory allocations from your
performance-critical code paths, Allocation Tracker can help you identify important issues
in your code. For example, an app might create a new
Paint
object on every draw.
Making the Paint
object global is a simple fix that helps improve performance.
Android Studio creates an allocation file with the filename
application-id_yyyy.mm.dd_hh.mm.alloc
,
opens the file in Android Studio, and adds the file to the Allocations list in the
Captures tab.
For more information about using Allocation Tracker, see Allocation Tracker.
For further analysis, you might want to observe how your app's memory is divided between different types of RAM allocation with the following adb command:
adb shell dumpsys meminfo <package_name|pid> [-d]
The -d flag prints more info related to Dalvik and ART memory usage.
The output lists all of your app's current allocations, measured in kilobytes.
When inspecting this information, you should be familiar with the following types of allocation:
A nice characteristic of the PSS measurement is that you can add up the PSS across all processes to determine the actual memory being used by all processes. This means PSS is a good measure for the actual RAM weight of a process and for comparison against the RAM use of other processes and the total available RAM.
For example, below is the the output for Map’s process on a Nexus 5 device. There is a lot of information here, but key points for discussion are listed below.
adb shell dumpsys meminfo com.google.android.apps.maps -d
Note: The information you see might vary slightly from what is shown here, because some details of the output differ across platform versions.
** MEMINFO in pid 18227 [com.google.android.apps.maps] ** Pss Private Private Swapped Heap Heap Heap Total Dirty Clean Dirty Size Alloc Free ------ ------ ------ ------ ------ ------ ------ Native Heap 10468 10408 0 0 20480 14462 6017 Dalvik Heap 34340 33816 0 0 62436 53883 8553 Dalvik Other 972 972 0 0 Stack 1144 1144 0 0 Gfx dev 35300 35300 0 0 Other dev 5 0 4 0 .so mmap 1943 504 188 0 .apk mmap 598 0 136 0 .ttf mmap 134 0 68 0 .dex mmap 3908 0 3904 0 .oat mmap 1344 0 56 0 .art mmap 2037 1784 28 0 Other mmap 30 4 0 0 EGL mtrack 73072 73072 0 0 GL mtrack 51044 51044 0 0 Unknown 185 184 0 0 TOTAL 216524 208232 4384 0 82916 68345 14570 Dalvik Details .Heap 6568 6568 0 0 .LOS 24771 24404 0 0 .GC 500 500 0 0 .JITCache 428 428 0 0 .Zygote 1093 936 0 0 .NonMoving 1908 1908 0 0 .IndirectRef 44 44 0 0 Objects Views: 90 ViewRootImpl: 1 AppContexts: 4 Activities: 1 Assets: 2 AssetManagers: 2 Local Binders: 21 Proxy Binders: 28 Parcel memory: 18 Parcel count: 74 Death Recipients: 2 OpenSSL Sockets: 2
Here is an older dumpsys on Dalvik of the gmail app:
** MEMINFO in pid 9953 [com.google.android.gm] ** Pss Pss Shared Private Shared Private Heap Heap Heap Total Clean Dirty Dirty Clean Clean Size Alloc Free ------ ------ ------ ------ ------ ------ ------ ------ ------ Native Heap 0 0 0 0 0 0 7800 7637(6) 126 Dalvik Heap 5110(3) 0 4136 4988(3) 0 0 9168 8958(6) 210 Dalvik Other 2850 0 2684 2772 0 0 Stack 36 0 8 36 0 0 Cursor 136 0 0 136 0 0 Ashmem 12 0 28 0 0 0 Other dev 380 0 24 376 0 4 .so mmap 5443(5) 1996 2584 2664(5) 5788 1996(5) .apk mmap 235 32 0 0 1252 32 .ttf mmap 36 12 0 0 88 12 .dex mmap 3019(5) 2148 0 0 8936 2148(5) Other mmap 107 0 8 8 324 68 Unknown 6994(4) 0 252 6992(4) 0 0 TOTAL 24358(1) 4188 9724 17972(2)16388 4260(2)16968 16595 336 Objects Views: 426 ViewRootImpl: 3(8) AppContexts: 6(7) Activities: 2(7) Assets: 2 AssetManagers: 2 Local Binders: 64 Proxy Binders: 34 Death Recipients: 0 OpenSSL Sockets: 1 SQL MEMORY_USED: 1739 PAGECACHE_OVERFLOW: 1164 MALLOC_SIZE: 62
In general, be concerned with only the Pss Total
and Private Dirty
columns. In some cases, the Private Clean
and Heap Alloc
columns also
offer interesting data. More information about the different memory allocations (the rows) you
should observe follows:
Dalvik Heap
Pss Total
includes all Zygote
allocations (weighted by their sharing across processes, as described in the PSS definition above).
The Private Dirty
number is the actual RAM committed to only your app’s heap, composed
of your own allocations and any Zygote allocation pages that have been modified since forking your
app’s process from Zygote.
Note: On newer platform versions that have the Dalvik
Other
section, the Pss Total
and Private Dirty
numbers for Dalvik
Heap do not include Dalvik overhead such as the just-in-time compilation (JIT) and GC
bookkeeping, whereas older versions list it all combined under Dalvik
.
The Heap Alloc
is the amount of memory that the Dalvik and native heap allocators
keep track of for your app. This value is larger than Pss Total
and Private
Dirty
because your process was forked from Zygote and it includes allocations that your
process shares with all the others.
.so mmap
and .dex mmap
.so
(native) and .dex
(Dalvik or ART)
code. The Pss Total
number includes platform code shared across apps; the
Private Clean
is your app’s own code. Generally, the actual mapped size will be much
larger—the RAM here is only what currently needs to be in RAM for code that has been executed by
the app. However, the .so mmap has a large private dirty, which is due to fix-ups to the native
code when it was loaded into its final address.
.oat mmap
.art mmap
Object
instances, it does not count
towards your heap size.
.Heap
(only with -d flag).LOS
(only with -d flag).GC
(only with -d flag).JITCache
(only with -d flag).Zygote
(only with -d flag).NonMoving
(only with -d flag).IndirectRef
(only with -d flag)Unknown
Pss Total
for Unknown takes into account sharing with Zygote, and Private
Dirty
is unknown RAM dedicated to only your app.
TOTAL
The Private Dirty
and Private Clean
are the total allocations within
your process, which are not shared with other processes. Together (especially
Private Dirty
), this is the amount of RAM that will be released back to the system when
your process is destroyed. Dirty RAM is pages that have been modified and so must stay committed to
RAM (because there is no swap); clean RAM is pages that have been mapped from a persistent file
(such as code being executed) and so can be paged out if not used for a while.
ViewRootImpl
AppContexts
and Activities
Context
and Activity
objects that
currently live in your process. This can help you to quickly identify leaked
Activity
objects that can’t be
garbage collected due to static references on them, which is common. These objects often have many
other allocations associated with them, which makes them a good way to track large memory leaks.Note: A View
or Drawable
object
also holds a reference to the Activity
that it's from, so holding a View
or
Drawable
object can
also lead to your app leaking an
Activity
.
While using the tools described above, you should aggressively stress your app code and try forcing memory leaks. One way to provoke memory leaks in your app is to let it run for a while before inspecting the heap. Leaks will trickle up to the top of the allocations in the heap. However, the smaller the leak, the longer you need to run the app in order to see it.
You can also trigger a memory leak in one of the following ways:
Activity
,
Context
, or
View
object because the system
recreates the Activity
and if your
app holds a reference to one of those objects somewhere else, the system can't garbage collect it.Tip: You can also perform the above steps by using the monkey test framework. For more information on running the monkey test framework, read the monkeyrunner documentation.