1 page.title=Investigating Your RAM Usage 2 page.tags=memory,OutOfMemoryError 3 @jd:body 4 5 <div id="qv-wrapper"> 6 <div id="qv"> 7 <h2>In this document</h2> 8 <ol> 9 <li><a href="#LogMessages">Interpreting Log Messages</a></li> 10 <li><a href="#ViewHeap">Viewing Heap Updates</a></li> 11 <li><a href="#TrackAllocations">Tracking Allocations</a></li> 12 <li><a href="#ViewingAllocations">Viewing Overall Memory Allocations</a></li> 13 <li><a href="#HeapDump">Capturing a Heap Dump</a></li> 14 <li><a href="#TriggerLeaks">Triggering Memory Leaks</a></li> 15 </ol> 16 <h2>See Also</h2> 17 <ul> 18 <li><a href="{@docRoot}training/articles/memory.html">Managing Your App's Memory</a></li> 19 </ul> 20 </div> 21 </div> 22 23 24 25 26 <p>Because Android is designed for mobile devices, you should always be careful about how much 27 random-access memory (RAM) your app uses. Although Androids Dalvik virtual machine performs 28 routine garbage collection, this doesnt mean you can ignore when and where your app allocates and 29 releases memory. In order to provide a stable user experience that allows the system to quickly 30 switch between apps, its important that your app does not needlessly consume memory when the user 31 is not interacting with it.</p> 32 33 <p>Even if you follow all the best practices for <a href="{@docRoot}training/articles/memory.html" 34 >Managing Your App Memory</a> during 35 development (which you should), you still might leak objects or introduce other memory bugs. The 36 only way to be certain your app is using as little memory as possible is to analyze your apps 37 memory usage with tools. This guide shows you how to do that.</p> 38 39 40 <h2 id="LogMessages">Interpreting Log Messages</h2> 41 42 <p>The simplest place to begin investigating your apps memory usage is the Dalvik log messages. You'll 43 find these log messages in <a href="{@docRoot}tools/help/logcat.html">logcat</a> (the output is 44 available in the Device Monitor or directly in IDEs such as Eclipse and Android Studio).</p> 45 46 <p>Every time a garbage collection occurs, logcat prints a message with the following information:</p> 47 48 <pre class="no-pretty-print"> 49 D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time> 50 </pre> 51 52 <dl> 53 <dt>GC Reason</dt> 54 <dd> 55 What triggered the garbage collection and what kind of collection it is. Reasons that may appear 56 include: 57 <dl> 58 <dt><code>GC_CONCURRENT</code></dt> 59 <dd>A concurrent garbage collection that frees up memory as your heap begins to fill up.</dd> 60 61 <dt><code>GC_FOR_MALLOC</code></dt> 62 <dd>A garbage collection caused because your app attempted to allocate memory when your heap was 63 already full, so the system had to stop your app and reclaim memory.</dd> 64 65 <dt><code>GC_HPROF_DUMP_HEAP</code></dt> 66 <dd>A garbage collection that occurs when you create an HPROF file to analyze your heap.</dd> 67 68 <dt><code>GC_EXPLICIT</code> 69 <dd>An explicit garbage collection, such as when you call {@link java.lang.System#gc()} (which you 70 should avoid calling and instead trust the garbage collector to run when needed).</dd> 71 72 <dt><code>GC_EXTERNAL_ALLOC</code></dt> 73 <dd>This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik 74 heap). A garbage collection for externally allocated memory (such as the pixel data stored in 75 native memory or NIO byte buffers).</dd> 76 </dl> 77 </dd> 78 79 <dt>Amount freed</dt> 80 <dd>The amount of memory reclaimed from this garbage collection.</dd> 81 82 <dt>Heap stats</dt> 83 <dd>Percentage free and (number of live objects)/(total heap size).</dd> 84 85 <dt>External memory stats</dt> 86 <dd>Externally allocated memory on API level 10 and lower (amount of allocated memory) / (limit at 87 which collection will occur).</dd> 88 89 <dt>Pause time</dt> 90 <dd>Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at the 91 beginning of the collection and another near the end.</dd> 92 </dl> 93 94 <p>For example:</p> 95 96 <pre class="no-pretty-print"> 97 D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms 98 </pre> 99 100 <p>As these log messages stack up, look out for increases in the heap stats (the 101 {@code 3571K/9991K} value in the above example). If this value 102 continues to increase and doesn't ever seem to get smaller, you could have a memory leak.</p> 103 104 105 <h2 id="ViewHeap">Viewing Heap Updates</h2> 106 107 <p>To get a little information about what kind of memory your app is using and when, you can view 108 real-time updates to your app's heap in the Device Monitor:</p> 109 110 <ol> 111 <li>Open the Device Monitor. 112 <p>From your <code><sdk>/tools/</code> directory, launch the <code>monitor</code> tool.</p> 113 </li> 114 <li>In the Debug Monitor window, select your app's process from the list on the left.</li> 115 <li>Click <strong>Update Heap</strong> above the process list.</li> 116 <li>In the right-side panel, select the <strong>Heap</strong> tab.</li> 117 </ol> 118 119 <p>The Heap view shows some basic stats about your heap memory usage, updated after every 120 garbage collection. To see the first update, click the <strong>Cause GC</strong> button.</p> 121 122 <img src="{@docRoot}images/tools/monitor-vmheap@2x.png" width="760" alt="" /> 123 <p class="img-caption"><strong>Figure 1.</strong> The Device Monitor tool, 124 showing the <strong>[1] Update Heap</strong> and <strong>[2] Cause GC</strong> buttons. 125 The Heap tab on the right shows the heap results.</p> 126 127 <p>Continue interacting with your app to watch your heap allocation update with each garbage 128 collection. This can help you identify which actions in your app are likely causing too much 129 allocation and where you should try to reduce allocations and release 130 resources.</p> 131 132 133 134 <h2 id="TrackAllocations">Tracking Allocations</h2> 135 136 <p>As you start narrowing down memory issues, you should also use the Allocation Tracker to 137 get a better understanding of where your memory-hogging objects are allocated. The Allocation 138 Tracker can be useful not only for looking at specific uses of memory, but also to analyze critical 139 code paths in an app such as scrolling.</p> 140 141 <p>For example, tracking allocations when flinging a list in your app allows you to see all the 142 allocations that need to be done for that behavior, what thread they are on, and where they came 143 from. This is extremely valuable for tightening up these paths to reduce the work they need and 144 improve the overall smoothness of the UI.</p> 145 146 <p>To use Allocation Tracker:</p> 147 <ol> 148 <li>Open the Device Monitor. 149 <p>From your <code><sdk>/tools/</code> directory, launch the <code>monitor</code> tool.</p> 150 </li> 151 <li>In the DDMS window, select your app's process in the left-side panel.</li> 152 <li>In the right-side panel, select the <strong>Allocation Tracker</strong> tab.</li> 153 <li>Click <strong>Start Tracking</strong>.</li> 154 <li>Interact with your app to execute the code paths you want to analyze.</li> 155 <li>Click <strong>Get Allocations</strong> every time you want to update the 156 list of allocations.</li> 157 </ol> 158 159 <p>The list shows all recent allocations, 160 currently limited by a 512-entry ring buffer. Click on a line to see the stack trace that led to 161 the allocation. The trace shows you not only what type of object was allocated, but also in which 162 thread, in which class, in which file and at which line.</p> 163 164 <img src="{@docRoot}images/tools/monitor-tracker@2x.png" width="760" alt="" /> 165 <p class="img-caption"><strong>Figure 2.</strong> The Device Monitor tool, 166 showing recent app allocations and stack traces in the Allocation Tracker.</p> 167 168 169 <p class="note"><strong>Note:</strong> You will always see some allocations from {@code 170 DdmVmInternal} and else where that come from the allocation tracker itself.</p> 171 172 <p>Although it's not necessary (nor possible) to remove all allocations for your performance 173 critical code paths, the allocation tracker can help you identify important issues in your code. 174 For instance, some apps might create a new {@link android.graphics.Paint} object on every draw. 175 Moving that object into a global member is a simple fix that helps improve performance.</p> 176 177 178 179 180 181 182 <h2 id="ViewingAllocations">Viewing Overall Memory Allocations</h2> 183 184 <p>For further analysis, you may want to observe how your app's memory is 185 divided between different types of RAM allocation with the 186 following <a href="{@docRoot}tools/help/adb.html">adb</a> command:</p> 187 188 <pre class="no-pretty-print"> 189 adb shell dumpsys meminfo <package_name> 190 </pre> 191 192 <p>The output lists all of your app's current allocations, measured in kilobytes.</p> 193 194 <p>When inspecting this information, you should be familiar with the 195 following types of allocation:</p> 196 197 <dl> 198 <dt>Private (Clean and Dirty) RAM</dt> 199 <dd>This is memory that is being used by only your process. This is the bulk of the RAM that the system 200 can reclaim when your apps process is destroyed. Generally, the most important portion of this is 201 private dirty RAM, which is the most expensive because it is used by only your process and its 202 contents exist only in RAM so cant be paged to storage (because Android does not use swap). All 203 Dalvik and native heap allocations you make will be private dirty RAM; Dalvik and native 204 allocations you share with the Zygote process are shared dirty RAM.</dd> 205 206 <dt>Proportional Set Size (PSS)</dt> 207 <dd>This is a measurement of your apps RAM use that takes into account sharing pages across processes. 208 Any RAM pages that are unique to your process directly contribute to its PSS value, while pages 209 that are shared with other processes contribute to the PSS value only in proportion to the amount 210 of sharing. For example, a page that is shared between two processes will contribute half of its 211 size to the PSS of each process.</dd> 212 </dl> 213 214 215 <p>A nice characteristic of the PSS measurement is that you can add up the PSS across all processes to 216 determine the actual memory being used by all processes. This means PSS is a good measure for the 217 actual RAM weight of a process and for comparison against the RAM use of other processes and the 218 total available RAM.</p> 219 220 221 <p>For example, below is the the output for Gmails process on a tablet device. There is a lot of 222 information here, but key points for discussion are listed below.</p> 223 224 <p class="note"><strong>Note:</strong> The information you see may vary slightly from what is shown 225 here, as some details of the output differ across platform versions.</p> 226 227 <pre class="no-pretty-print"> 228 ** MEMINFO in pid 9953 [com.google.android.gm] ** 229 Pss Pss Shared Private Shared Private Heap Heap Heap 230 Total Clean Dirty Dirty Clean Clean Size Alloc Free 231 ------ ------ ------ ------ ------ ------ ------ ------ ------ 232 Native Heap 0 0 0 0 0 0 7800 7637(6) 126 233 Dalvik Heap 5110(3) 0 4136 4988(3) 0 0 9168 8958(6) 210 234 Dalvik Other 2850 0 2684 2772 0 0 235 Stack 36 0 8 36 0 0 236 Cursor 136 0 0 136 0 0 237 Ashmem 12 0 28 0 0 0 238 Other dev 380 0 24 376 0 4 239 .so mmap 5443(5) 1996 2584 2664(5) 5788 1996(5) 240 .apk mmap 235 32 0 0 1252 32 241 .ttf mmap 36 12 0 0 88 12 242 .dex mmap 3019(5) 2148 0 0 8936 2148(5) 243 Other mmap 107 0 8 8 324 68 244 Unknown 6994(4) 0 252 6992(4) 0 0 245 TOTAL 24358(1) 4188 9724 17972(2)16388 4260(2)16968 16595 336 246 247 Objects 248 Views: 426 ViewRootImpl: 3(8) 249 AppContexts: 6(7) Activities: 2(7) 250 Assets: 2 AssetManagers: 2 251 Local Binders: 64 Proxy Binders: 34 252 Death Recipients: 0 253 OpenSSL Sockets: 1 254 255 SQL 256 MEMORY_USED: 1739 257 PAGECACHE_OVERFLOW: 1164 MALLOC_SIZE: 62 258 </pre> 259 260 <p>Generally, you should be concerned with only the <code>Pss Total</code> and <code>Private Dirty</code> 261 columns. In some cases, the <code>Private Clean</code> and <code>Heap Alloc</code> columns also offer 262 interesting data. Here is some more information about the different memory allocations (the rows) 263 you should observe: 264 265 <dl> 266 <dt><code>Dalvik Heap</code></dt> 267 <dd>The RAM used by Dalvik allocations in your app. The <code>Pss Total</code> includes all Zygote 268 allocations (weighted by their sharing across processes, as described in the PSS definition above). 269 The <code>Private Dirty</code> number is the actual RAM committed to only your apps heap, composed of 270 your own allocations and any Zygote allocation pages that have been modified since forking your 271 apps process from Zygote. 272 273 <p class="note"><strong>Note:</strong> On newer platform versions that have the <code>Dalvik 274 Other</code> section, the <code>Pss Total</code> and <code>Private Dirty</code> numbers for Dalvik Heap do 275 not include Dalvik overhead such as the just-in-time compilation (JIT) and garbage collection (GC) 276 bookkeeping, whereas older versions list it all combined under <code>Dalvik</code>.</p> 277 278 <p>The <code>Heap Alloc</code> is the amount of memory that the Dalvik and native heap allocators keep 279 track of for your app. This value is larger than <code>Pss Total</code> and <code>Private Dirty</code> 280 because your process was forked from Zygote and it includes allocations that your process shares 281 with all the others.</p> 282 </dd> 283 284 <dt><code>.so mmap</code> and <code>.dex mmap</code></dt> 285 <dd>The RAM being used for mmapped <code>.so</code> (native) and <code>.dex</code> (Dalvik) code. The 286 <code>Pss Total</code> number includes platform code shared across apps; the <code>Private Clean</code> is 287 your apps own code. Generally, the actual mapped size will be much largerthe RAM here is only 288 what currently needs to be in RAM for code that has been executed by the app. However, the .so mmap 289 has a large private dirty, which is due to fix-ups to the native code when it was loaded into its 290 final address. 291 </dd> 292 293 <dt><code>Unknown</code></dt> 294 <dd>Any RAM pages that the system could not classify into one of the other more specific items. 295 Currently, this contains mostly native allocations, which cannot be identified by the tool when 296 collecting this data due to Address Space Layout Randomization (ASLR). As with the Dalvik heap, the 297 <code>Pss Total</code> for Unknown takes into account sharing with Zygote, and <code>Private Dirty</code> 298 is unknown RAM dedicated to only your app. 299 </dd> 300 301 <dt><code>TOTAL</code></dt> 302 <dd>The total Proportional Set Size (PSS) RAM used by your process. This is the sum of all PSS fields 303 above it. It indicates the overall memory weight of your process, which can be directly compared 304 with other processes and the total available RAM. 305 306 <p>The <code>Private Dirty</code> and <code>Private Clean</code> are the total allocations within your 307 process, which are not shared with other processes. Together (especially <code>Private Dirty</code>), 308 this is the amount of RAM that will be released back to the system when your process is destroyed. 309 Dirty RAM is pages that have been modified and so must stay committed to RAM (because there is no 310 swap); clean RAM is pages that have been mapped from a persistent file (such as code being 311 executed) and so can be paged out if not used for a while.</p> 312 313 </dd> 314 315 <dt><code>ViewRootImpl</code></dt> 316 <dd>The number of root views that are active in your process. Each root view is associated with a 317 window, so this can help you identify memory leaks involving dialogs or other windows. 318 </dd> 319 320 <dt><code>AppContexts</code> and <code>Activities</code></dt> 321 <dd>The number of app {@link android.content.Context} and {@link android.app.Activity} objects that 322 currently live in your process. This can be useful to quickly identify leaked {@link 323 android.app.Activity} objects that cant be garbage collected due to static references on them, 324 which is common. These objects often have a lot of other allocations associated with them and so 325 are a good way to track large memory leaks.</dd> 326 327 <p class="note"><strong>Note:</strong> A {@link android.view.View} or {@link 328 android.graphics.drawable.Drawable} object also holds a reference to the {@link 329 android.app.Activity} that it's from, so holding a {@link android.view.View} or {@link 330 android.graphics.drawable.Drawable} object can also lead to your app leaking an {@link 331 android.app.Activity}.</p> 332 333 </dd> 334 </dl> 335 336 337 338 339 340 341 342 343 344 <h2 id="HeapDump">Capturing a Heap Dump</h2> 345 346 <p>A heap dump is a snapshot of all the objects in your app's heap, stored in a binary format called 347 HPROF. Your app's heap dump provides information about the overall state of your app's heap so you 348 can track down problems you might have identified while viewing heap updates.</p> 349 350 <p>To retrieve your heap dump:</p> 351 <ol> 352 <li>Open the Device Monitor. 353 <p>From your <code><sdk>/tools/</code> directory, launch the <code>monitor</code> tool.</p> 354 </li> 355 <li>In the DDMS window, select your app's process in the left-side panel.</li> 356 <li>Click <strong>Dump HPROF file</strong>, shown in figure 3.</li> 357 <li>In the window that appears, name your HPROF file, select the save location, 358 then click <strong>Save</strong>.</li> 359 </ol> 360 361 <img src="{@docRoot}images/tools/monitor-hprof@2x.png" width="760" alt="" /> 362 <p class="img-caption"><strong>Figure 3.</strong> The Device Monitor tool, 363 showing the <strong>[1] Dump HPROF file</strong> button.</p> 364 365 <p>If you need to be more precise about when the dump is created, you can also create a heap dump 366 at the critical point in your app code by calling {@link android.os.Debug#dumpHprofData 367 dumpHprofData()}.</p> 368 369 <p>The heap dump is provided in a format that's similar to, but not identical to one from the Java 370 HPROF tool. The major difference in an Android heap dump is due to the fact that there are a large 371 number of allocations in the Zygote process. But because the Zygote allocations are shared across 372 all app processes, they dont matter very much to your own heap analysis.</p> 373 374 <p>To analyze your heap dump, you can use a standard tool like jhat or the <a href= 375 "http://www.eclipse.org/mat/downloads.php">Eclipse Memory Analyzer Tool</a> (MAT). However, first 376 you'll need to convert the HPROF file from Android's format to the J2SE HPROF format. You can do 377 this using the <code>hprof-conv</code> tool provided in the <code><sdk>/tools/</code> 378 directory. Simply run the <code>hprof-conv</code> command with two arguments: the original HPROF 379 file and the location to write the converted HPROF file. For example:</p> 380 381 <pre class="no-pretty-print"> 382 hprof-conv heap-original.hprof heap-converted.hprof 383 </pre> 384 385 <p class="note"><strong>Note:</strong> If you're using the version of DDMS that's integrated into 386 Eclipse, you do not need to perform the HPROF converstionit performs the conversion by 387 default.</p> 388 389 <p>You can now load the converted file in MAT or another heap analysis tool that understands 390 the J2SE HPROF format.</p> 391 392 <p>When analyzing your heap, you should look for memory leaks caused by:</p> 393 <ul> 394 <li>Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold a 395 reference to the container Activity or Context.</li> 396 <li>Non-static inner classes (such as a Runnable, which can hold the Activity instance).</li> 397 <li>Caches that hold objects longer than necessary.</li> 398 </ul> 399 400 401 <h3 id="EclipseMat">Using the Eclipse Memory Analyzer Tool</h3> 402 403 <p>The <a href= 404 "http://www.eclipse.org/mat/downloads.php">Eclipse Memory Analyzer Tool</a> (MAT) is just one 405 tool that you can use to analyze your heap dump. It's also quite powerful so most of its 406 capabilities are beyond the scope of this document, but here are a few tips to get you started. 407 408 <p>Once you open your converted HPROF file in MAT, you'll see a pie chart in the Overview, 409 showing what your largest objects are. Below this chart, are links to couple of useful features:</p> 410 411 <ul> 412 <li>The <strong>Histogram view</strong> shows a list of all classes and how many instances 413 there are of each. 414 <p>You might want to use this view to find extra instances of classes for which you know there 415 should be only a certain number. For example, a common source of leaks is additional instance of 416 your {@link android.app.Activity} class, for which you should usually have only one instance 417 at a time. To find a specific class instance, type the class name into the <em><Regex></em> 418 field at the top of the list. 419 <p>When you find a class with too many instances, right-click it and select 420 <strong>List objects</strong> > <strong>with incoming references</strong>. In the list that 421 appears, you can determine where an instance is retained by right-clicking it and selecting 422 <strong>Path To GC Roots</strong> > <strong>exclude weak references</strong>.</p> 423 </li> 424 425 <li>The <strong>Dominator tree</strong> shows a list of objects organized by the amount 426 of retained heap. 427 <p>What you should look for is anything that's retaining a portion of heap that's roughly 428 equivalent to the memory size you observed leaking from the <a href="#LogMessages">GC logs</a>, 429 <a href="#ViewHeap">heap updates</a>, or <a href="#TrackAllocations">allocation 430 tracker</a>. 431 <p>When you see something suspicious, right-click on the item and select 432 <strong>Path To GC Roots</strong> > <strong>exclude weak references</strong>. This opens a 433 new tab that traces the references to that object which is causing the alleged leak.</p> 434 435 <p class="note"><strong>Note:</strong> Most apps will show an instance of 436 {@link android.content.res.Resources} near the top with a good chunk of heap, but this is 437 usually expected when your app uses lots of resources from your {@code res/} directory.</p> 438 </li> 439 </ul> 440 441 442 <img src="{@docRoot}images/tools/mat-histogram@2x.png" width="760" alt="" /> 443 <p class="img-caption"><strong>Figure 4.</strong> The Eclipse Memory Analyzer Tool (MAT), 444 showing the Histogram view and a search for "MainActivity".</p> 445 446 <p>For more information about MAT, watch the Google I/O 2011 presentation, 447 <a href="http://www.youtube.com/watch?v=_CruQY55HOk">Memory management for Android apps</a>, 448 which includes a walkthrough using MAT beginning at about <a href= 449 "http://www.youtube.com/watch?v=_CruQY55HOk&feature=player_detailpage#t=1270">21:10</a>. 450 Also refer to the <a href="http://wiki.eclipse.org/index.php/MemoryAnalyzer">Eclipse Memory 451 Analyzer documentation</a>.</p> 452 453 <h4 id="MatCompare">Comparing heap dumps</h4> 454 455 <p>You may find it useful to compare your app's heap state at two different points in time in order 456 to inspect the changes in memory allocation. To compare two heap dumps using MAT:</p> 457 458 <ol> 459 <li>Create two HPROF files as described above, in <a href="#HeapDump">Capturing a Heap Dump</a>. 460 <li>Open the first HPROF file in MAT (<strong>File</strong> > <strong>Open Heap Dump</strong>). 461 <li>In the Navigation History view (if not visible, select <strong>Window</strong> > 462 <strong>Navigation History</strong>), right-click on <strong>Histogram</strong> and select 463 <strong>Add to Compare Basket</strong>. 464 <li>Open the second HPROF file and repeat steps 2 and 3. 465 <li>Switch to the <em>Compare Basket</em> view and click <strong>Compare the Results</strong> 466 (the red "!" icon in the top-right corner of the view). 467 </ol> 468 469 470 471 472 473 474 <h2 id="TriggerLeaks">Triggering Memory Leaks</h2> 475 476 <p>While using the tools described above, you should aggressively stress your app code and try 477 forcing memory leaks. One way to provoke memory leaks in your app is to let it 478 run for a while before inspecting the heap. Leaks will trickle up to the top of the allocations in 479 the heap. However, the smaller the leak, the longer you need to run the app in order to see it.</p> 480 481 <p>You can also trigger a memory leak in one of the following ways:</p> 482 <ol> 483 <li>Rotate the device from portrait to landscape and back again multiple times while in different 484 activity states. Rotating the device can often cause an app to leak an {@link android.app.Activity}, 485 {@link android.content.Context}, or {@link android.view.View} object because the system 486 recreates the {@link android.app.Activity} and if your app holds a reference 487 to one of those objects somewhere else, the system can't garbage collect it.</li> 488 <li>Switch between your app and another app while in different activity states (navigate to 489 the Home screen, then return to your app).</li> 490 </ol> 491 492 <p class="note"><strong>Tip:</strong> You can also perform the above steps by using the "monkey" 493 test framework. For more information on running the monkey test framework, read the <a href= 494 "{@docRoot}tools/help/monkeyrunner_concepts.html">monkeyrunner</a> 495 documentation.</p> 496