Home | History | Annotate | Download | only in performance
      1 page.title=Overview of Android Memory Management
      2 page.tags=ram,memory,paging,mmap
      3 
      4 @jd:body
      5 
      6 <div id="qv-wrapper">
      7 <div id="qv">
      8 
      9 <h2>In this document</h2>
     10 <ol class="nolist">
     11   <li><a href="#gc">Garbage collection</a></li>
     12   <li><a href="#SharingRAM">Sharing Memory</a></li>
     13   <li><a href="#AllocatingRAM">Allocating and Reclaiming App Memory</a></li>
     14   <li><a href="#RestrictingMemory">Restricting App Memory</a></li>
     15   <li><a href="#SwitchingApps">Switching Apps</a></li>
     16 </ol>
     17 <h2>See Also</h2>
     18 <ul>
     19   <li><a href="{@docRoot}training/articles/memory.html">Manage Your App's Memory</a>
     20   </li>
     21   <li><a href="{@docRoot}studio/profile/investigate-ram.html">Investigating Your RAM Usage</a>
     22   </li>
     23 </ul>
     24 
     25 </div>
     26 </div>
     27 
     28 <p>
     29   The Android Runtime (ART) and Dalvik virtual machine use
     30   <a href="http://en.wikipedia.org/wiki/Paging" class="external-link">paging</a>
     31   and <a href="http://en.wikipedia.org/wiki/Memory-mapped_files" class="external-link">memory-mapping</a>
     32   (mmapping) to manage memory. This means that any memory an app
     33   modifies&mdash;whether by allocating
     34   new objects or touching mmapped pages&mdash;remains resident in RAM and
     35   cannot be paged out. The only way to release memory from an app is to release
     36   object references that the app holds, making the memory available to the
     37   garbage collector.
     38   That is with one exception: any files
     39   mmapped in without modification, such as code,
     40   can be paged out of RAM if the system wants to use that memory elsewhere.
     41 </p>
     42 
     43 <p>
     44   This page explains how Android manages app processes and memory
     45   allocation. For more information about how to manage memory more efficiently
     46   in your app, see
     47   <a href="{@docRoot}training/articles/memory.html">Manage Your App's Memory</a>.
     48 </p>
     49 
     50 <!-- Section 1 #################################################### -->
     51 
     52 <h2 id="gc">Garbage collection</h2>
     53 
     54 <p>
     55   A managed memory environment, like the ART or Dalvik virtual machine,
     56   keeps track of each memory allocation. Once it determines
     57   that a piece of memory is no longer being used by the program,
     58   it frees it back to the heap, without any intervention from the programmer.
     59   The mechanism for reclaiming unused memory
     60   within a managed memory environment
     61   is known as <i>garbage collection</i>. Garbage collection has two goals:
     62   find data objects in a program that cannot be accessed in the future; and
     63   reclaim the resources used by those objects.
     64 </p>
     65 
     66 <p>
     67   Androids memory heap is a generational one, meaning that there are
     68   different buckets of allocations that it tracks,
     69   based on the expected life and size of an object being allocated.
     70   For example, recently allocated objects belong in the <i>Young generation</i>.
     71   When an object stays active long enough, it can be promoted
     72   to an older generation, followed by a permanent generation.
     73 </p>
     74 
     75 <p>
     76   Each heap generation has its own dedicated upper limit on the amount
     77   of memory that objects there can occupy. Any time a generation starts
     78   to fill up, the system executes a garbage collection
     79   event in an attempt to free up memory. The duration of the garbage collection
     80   depends on which generation of objects it's collecting
     81   and how many active objects are in each generation.
     82 </p>
     83 
     84 <p>
     85   Even though garbage collection can be quite fast, it can still
     86   affect your app's performance. You dont generally control
     87   when a garbage collection event occurs from within your code.
     88   The system has a running set of criteria for determining when to perform
     89   garbage collection. When the criteria are satisfied,
     90   the system stops executing the process and begins garbage collection. If
     91   garbage collection occurs in the middle of an intensive processing loop
     92   like an animation or during music playback, it can increase processing time.
     93   This increase can potentially push code execution in your app past the
     94   recommended 16ms threshold for efficient and smooth frame rendering.
     95 </p>
     96 
     97 <p>
     98   Additionally, your code flow may perform kinds of work that
     99   force garbage collection events to occur
    100   more often or make them last longer-than-normal.
    101   For example, if you allocate multiple objects in the
    102   innermost part of a for-loop during each frame of an alpha
    103   blending animation, you might pollute your memory heap with a
    104   lot of objects.
    105   In that circumstance, the garbage collector executes multiple garbage
    106   collection events and can degrade the performance of your app.
    107 </p>
    108 
    109 <p>
    110   For more general information about garbage collection, see
    111   <a href="https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)"
    112   class="external-link">Garbage collection</a>.
    113 </p>
    114 
    115 <!-- Section 2 #################################################### -->
    116 
    117 <h2 id="SharingRAM">Sharing Memory</h2>
    118 
    119 <p>
    120   In order to fit everything it needs in RAM,
    121   Android tries to share RAM pages across processes. It
    122   can do so in the following ways:
    123 </p>
    124 
    125 <ul>
    126   <li>
    127     Each app process is forked from an existing process called Zygote.
    128     The Zygote process starts when the system boots and loads common
    129     framework code and resources
    130     (such as activity themes). To start a new app process,
    131     the system forks the Zygote process then
    132     loads and runs the app's code in the new process.
    133     This approach allows most of the RAM pages allocated for
    134     framework code and resources to be shared across all app processes.
    135   </li>
    136 
    137   <li>
    138     Most static data is mmapped into a process.
    139     This technique allows data to be shared
    140     between processes, and also allows it to be paged
    141     out when needed. Example static data include:
    142     Dalvik code (by placing it in a pre-linked <code>.odex</code>
    143     file for direct mmapping), app resources
    144     (by designing the resource table to be a structure
    145     that can be mmapped and by aligning the zip
    146     entries of the APK), and traditional project
    147     elements like native code in <code>.so</code> files.
    148   </li>
    149 
    150   <li>
    151     In many places, Android shares the same dynamic
    152     RAM across processes using explicitly allocated
    153     shared memory regions (either with ashmem or gralloc).
    154     For example, window surfaces use shared
    155     memory between the app and screen compositor, and
    156     cursor buffers use shared memory between the
    157     content provider and client.
    158   </li>
    159 </ul>
    160 
    161 <p>
    162   Due to the extensive use of shared memory, determining
    163   how much memory your app is using requires
    164   care. Techniques to properly determine your app's
    165   memory use are discussed in
    166   <a href="{@docRoot}studio/profile/investigate-ram.html">Investigating Your RAM Usage</a>.
    167 </p>
    168 
    169 <!-- Section 3 #################################################### -->
    170 
    171 <h2 id="AllocatingRAM">Allocating and Reclaiming App Memory</h2>
    172 
    173 <p>
    174   The Dalvik heap is constrained to a
    175   single virtual memory range for each app process. This defines
    176   the logical heap size, which can grow as it needs to
    177   but only up to a limit that the system defines
    178   for each app.
    179 </p>
    180 
    181 <p>
    182   The logical size of the heap is not the same as
    183   the amount of physical memory used by the heap.
    184   When inspecting your app's heap, Android computes
    185   a value called the Proportional Set Size (PSS),
    186   which accounts for both dirty and clean pages
    187   that are shared with other processesbut only in an
    188   amount that's proportional to how many apps share
    189   that RAM. This (PSS) total is what the system
    190   considers to be your physical memory footprint.
    191   For more information about PSS, see the
    192   <a href="{@docRoot}studio/profile/investigate-ram.html">Investigating Your RAM Usage</a>
    193   guide.
    194 </p>
    195 
    196 <p>
    197   The Dalvik heap does not compact the logical
    198   size of the heap, meaning that Android does not
    199   defragment the heap to close up space. Android
    200   can only shrink the logical heap size when there
    201   is unused space at the end of the heap. However,
    202   the system can still reduce physical memory used by the heap.
    203   After garbage collection, Dalvik
    204   walks the heap and finds unused pages, then returns
    205   those pages to the kernel using madvise. So, paired
    206   allocations and deallocations of large
    207   chunks should result in reclaiming all (or nearly all)
    208   the physical memory used. However,
    209   reclaiming memory from small allocations can be much
    210   less efficient because the page used
    211   for a small allocation may still be shared with
    212   something else that has not yet been freed.
    213 
    214 </p>
    215 
    216 <!-- Section 4 #################################################### -->
    217 
    218 <h2 id="RestrictingMemory">Restricting App Memory</h2>
    219 
    220 <p>
    221   To maintain a functional multi-tasking environment,
    222   Android sets a hard limit on the heap size
    223   for each app. The exact heap size limit varies
    224   between devices based on how much RAM the device
    225   has available overall. If your app has reached the
    226   heap capacity and tries to allocate more
    227   memory, it can receive an {@link java.lang.OutOfMemoryError}.
    228 </p>
    229 
    230 <p>
    231   In some cases, you might want to query the
    232   system to determine exactly how much heap space you
    233   have available on the current devicefor example, to
    234   determine how much data is safe to keep in a
    235   cache. You can query the system for this figure by calling
    236   {@link android.app.ActivityManager#getMemoryClass() }.
    237   This method returns an integer indicating the number of
    238   megabytes available for your app's heap.
    239 </p>
    240 
    241 <!-- Section 5 #################################################### -->
    242 
    243 <h2 id="SwitchingApps">Switching apps</h2>
    244 
    245 <p>
    246   When users switch between apps,
    247   Android keeps apps that
    248   are not foreground&mdash;that is, not visible to the user or running a
    249   foreground service like music playback&mdash;
    250   in a least-recently used (LRU) cache.
    251   For example, when a user first launches an app,
    252   a process is created for it; but when the user
    253   leaves the app, that process does <em>not</em> quit.
    254   The system keeps the process cached. If
    255   the user later returns to the app, the system reuses the process, thereby
    256   making the app switching faster.
    257 </p>
    258 
    259 <p>
    260   If your app has a cached process and it retains memory
    261   that it currently does not need,
    262   then your app&mdash;even while the user is not using it&mdash;
    263   affects the system's
    264   overall performance. As the system runs low on memory,
    265   it kills processes in the LRU cache
    266   beginning with the process least recently used. The system also
    267   accounts for processes that hold onto the most memory
    268   and can terminate them to free up RAM.
    269 </p>
    270 
    271 <p class="note">
    272   <strong>Note:</strong> When the system begins killing processes in the
    273   LRU cache, it primarily works bottom-up. The system also considers which
    274   processes consume more memory and thus provide the system
    275   more memory gain if killed.
    276   The less memory you consume while in the LRU list overall,
    277   the better your chances are
    278   to remain in the list and be able to quickly resume.
    279 </p>
    280 
    281 <p>
    282   For more information about how processes are cached while
    283   not running in the foreground and how
    284   Android decides which ones
    285   can be killed, see the
    286   <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and Threads</a>
    287   guide.
    288 </p>
    289