SlideShare a Scribd company logo
1 of 48
Download to read offline
Memory	
  Management	
  Fundamentals	
  
           for	
  Android	
  apps	
  
Agenda	
  
1.  Memory	
  usage	
  model	
  
   –  Constraints	
  	
  
   –  Zygote,	
  Dalvik	
  and	
  GC	
  
2.  Tools	
  for	
  memory	
  diagnos@cs	
  
   –      adb	
  shell	
  procrank	
  
   –      lava.lang.Run@me	
  
   –      Log	
  messages	
  
   –      Alloca@on	
  tracker	
  
   –      Eclipse	
  MAT	
  

   	
  
We’ve	
  grown	
  bigger	
  and	
  stronger	
  




                                  12x	
  RAM	
  	
  

 T-­‐Mobile	
  G1	
  (2008)	
                           Nexus	
  4	
  
                                                        (2012)	
  

192	
  MB	
                                            2	
  GB	
  
So	
  why	
  should	
  we	
  care	
  about	
  the	
  
                     memory?	
  
•  Heap	
  size	
  is	
  limited	
  and	
  device	
  dependent	
  
•  Screen	
  size	
  has	
  grown	
  drama@cally	
  -­‐	
  Bitmaps	
  
•  System	
  libraries	
  occupy	
  significant	
  amount	
  of	
  
   storage	
  
•  The	
  more	
  memory	
  we	
  use,	
  the	
  more	
  work	
  GC	
  
   has,	
  the	
  more	
  work	
  GC	
  has	
  the	
  bigger	
  pause	
  
   @me	
  will	
  be.	
  
•  BaWery	
  life	
  
Dalvik	
  VM	
  
Dalvik	
  VM	
  .dex	
  format	
  
Respect	
  the	
  balance!	
  
                                                               Cache	
  as	
  
                                                              much	
  useful	
  
     Use	
  as	
  liWle	
  
                                                              data	
  as	
  you	
  
     memory	
  as	
                                               can	
  
      you	
  can	
  
                                                                        Why?	
  

       Why?	
  

                                                           I	
  can	
  do	
  
I	
  will	
  kill	
  your	
  process	
  as	
           mul@tasking	
  and	
  I	
  
     soon	
  as	
  I	
  don’t	
  have	
                want	
  smooth	
  UX	
  
 memory	
  for	
  other	
  apps	
  
and	
  your	
  app	
  uses	
  lots	
  of	
  
                                                        when	
  switching	
  
                 memory	
                               between	
  apps	
  
Mark-­‐and-­‐sweep	
  GC	
  
Larger	
  heap	
  =	
  larger	
  pause	
  @me	
  =	
  
poor	
  performance	
  
Mark-­‐and-­‐sweep	
  GC	
  
                                    GC	
  
                                   Roots	
  


Phase	
  1	
  
Before	
  GC	
  
Mark-­‐and-­‐sweep	
  GC	
  
                                                                                            GC	
  
   Phase	
  2	
                                                                            Roots	
  
   Marking	
  complete	
  	
  



           -­‐	
  Marked	
  object	
  


            -­‐	
  Garbage	
  


Mark:	
  star@ng	
  from	
  roots,	
  mark	
  all	
  reachable	
  objects	
  by	
  using	
  a	
  depth-­‐first-­‐search	
  
pointer	
  traversal	
  
Mark-­‐and-­‐sweep	
  GC	
  
                                                                                          GC	
  
Phase	
  3	
                                                                             Roots	
  
Sweep	
  complete	
  	
  



      -­‐	
  Marked	
  object	
  




Sweep:	
  scan	
  the	
  heap	
  from	
  the	
  beginning	
  to	
  the	
  end	
  and	
  reclaim	
  the	
  
unmarked	
  objects	
  (and	
  unmark	
  the	
  marked	
  objects).	
  
GC	
  Improvements	
  




          Before	
                                       Aber	
  
                                 Garbage	
  collector	
  
•  Stop-­‐the-­‐world	
                     •  Advantage	
  of	
  mul@core	
  support	
  
•  Full	
  heap	
  collec@on	
              •  Mostly	
  concurrent	
  
•  Large	
  pause	
  @mes	
                 •  Par@al	
  collec@ons	
  
                                            •  Smaller	
  pause	
  @mes	
  
GC	
  Improvements	
  
                                                         Aber	
  
            Before	
  

•  Stop-­‐the-­‐world	
  –	
  
   all	
  app	
  threads	
  are	
  
   stopped	
  
•  Full	
  heap	
  collec@on	
  
•  Large	
  pause	
  @mes	
  
   oben	
  >	
  100ms	
  
                                      •    Ini4al	
  mark	
  -­‐	
  stop-­‐the-­‐world	
  
                                      •    Mark	
  -­‐	
  concurrent	
  
                                      •    Remark	
  –	
  stop-­‐the-­‐world	
  
                                      •    Sweep	
  -­‐	
  concurrent	
  
Healthy	
  memory	
  usage	
  paWern	
  
                                                                                         Maximum	
  
                                                                                         heap*	
  size	
  



Allocated	
  	
                                                    GC	
  Run	
  
memory	
  


                                                                                                                        Garbage	
  



                                                                                                                        Memory	
  
                                                                                                                        Usage	
  




                                                                                                             Time	
  
*	
  Maximum	
  amount	
  of	
  memory	
  our	
  app	
  is	
  allowed	
  to	
  use	
  
Edge	
  case	
  
                                                                                                           Maximum	
  
                                                                                                           heap*	
  size	
     OutOfMemoryError	
  



Allocated	
  	
                                                                            GC	
  Run	
  
memory	
  


                                                                                                                                               Garbage	
  



                                                                                                                                               Memory	
  
                                                                                                                                               Usage	
  




                                                                                                                                    Time	
  
*	
  Maximum	
  amount	
  of	
  memory	
  our	
  app	
  is	
  allowed	
  to	
  use	
  
Are	
  we	
  leaking	
  memory?	
  
                                                                                                                      Maximum	
  heap*	
  size	
  



    Allocated	
  	
                                                                         GC	
  Run	
  
    memory	
  


                                                                                                                                                         Garbage	
  
                                                                                                            Amount	
  of	
  memory	
  
                                                                                                            leaking	
  
                                                                                                                                                         Memory	
  
                                                                                                                                                         Usage	
  




                                                                                         Memory	
  leak	
                                     Time	
  
*	
  Maximum	
  amount	
  of	
  memory	
  our	
  app	
  is	
  allowed	
  to	
  use	
  
Maximum	
  heap	
  size	
  
                So	
  how	
  much	
  memory	
  can	
  we	
  actually	
  use?	
  
                                                   	
  
1.	
  ActivityManager.getMemoryClass()	
  –	
  	
  device	
  dependent	
  –	
  
always	
  constant	
  
2.	
  Runtime.getRuntime().maxMemory()	
  –	
  	
  can	
  be	
  changed	
  on	
  
rooted	
  devices,	
  is	
  slightly	
  larger	
  
	
  
	
  
	
  




  T-­‐Mobile	
  G1	
  –	
  16	
  MB	
     Nexus	
  One	
  –	
  32	
  MB	
     Nexus	
  7	
  –	
  64	
  MB	
  	
  
Memory	
  intensive	
  apps	
  
What	
  if	
  it	
  is	
  not	
  enough?	
  Image	
  editor?	
  Video	
  
editor?	
  3D	
  game?	
  
	
  
<application	
  
     	
  android:largeHeap=“true”	
  
</application>	
  
	
  
Use	
  only	
  if	
  you	
  are	
  sure	
  you	
  need	
  this	
  extra	
  
memory.	
  
	
  
ActivityManager.getLargeMemoryClass()	
  
	
  
We	
  are	
  armed	
  
Target	
  –	
  Honeycomb	
  Gallery	
  App	
  




   YOUR_SDK_LOCATIONsamplesandroid-­‐XXHoneycombGallery	
  
Tools	
  to	
  diagnose	
  memory	
  usage	
  
1.  adb	
  shell	
  procrank	
  
2.  java.lang.Run@me	
  
3.  Log	
  messages	
  
4.  Alloca@on	
  tracker	
  and	
  heap	
  updates	
  
5.  Heap	
  dumps	
  and	
  Eclipse	
  Memory	
  Analyzer	
  
    Tool	
  (MAT)	
  
procrank	
  u@lity	
  
Applica4on:	
  answers	
  a	
  ques@on	
  how	
  
much	
  memory	
  are	
  we	
  actually	
  using.	
  
procrank	
  
Lists	
  of	
  all	
  processes	
  on	
  the	
  device	
  and	
  memory	
  
they	
  are	
  using	
  (sorted	
  desc.).	
  
	
  
adb	
  shell	
  procrank	
  (requires	
  root	
  access)	
  
	
  
Uss	
  –	
  Unique	
  set	
  size	
  –	
  rough	
  memory	
  amount	
  
the	
  system	
  would	
  reclaim	
  if	
  it	
  kills	
  the	
  process.	
  
Java.lang.Run@me	
  methods	
  
•  freeMemory()	
  
•  totalMemory()	
  

 Applica4on:	
  	
  
 •  observing	
  general	
  applica@on	
  memory	
  usage	
  
    paWern	
  at	
  run@me	
  
 •  provides	
  basic	
  understanding	
  of	
  memory	
  usage	
  
    behavior	
  
 	
  	
  	
  	
  	
  	
  Observing	
  memory	
  state	
  changes	
  
                                      in	
  LogCat	
  
new Thread(new Runnable() {
           @Override
           public void run() {
               while (true) {
                   try {
                       Thread.sleep(5000);
                   } catch (InterruptedException e) {
                       // do nothing
                   }
                   reportMemoryUsage();
               }
           }
       }, “MemoryUsageReporter").start();	
  
 
Gives	
  a	
  general	
  idea	
  about	
  memory	
  
              changes	
  at	
  run@me	
  
 RAM	
  USAGE	
  free:	
  1.96MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.95MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.71MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.71MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  4.62MB,	
  total:	
  17.35MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  4.62MB,	
  total:	
  17.35MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.95MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.95MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 RAM	
  USAGE	
  free:	
  1.95MB,	
  total:	
  14.68MB,	
  max	
  :	
  64.00	
  
 	
  
Interpre@ng	
  LogCat	
  messages	
  

02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  
GC_CONCURRENT	
  freed	
  1536K,	
  17%	
  free	
  10790K/
12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  
General	
  informa@on	
  
 02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  
 GC_CONCURRENT	
  freed	
  1536K,	
  17%	
  free	
  10790K/
 12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  

•    Timestamp	
  
•    Logging	
  level	
  
•    Log	
  tag	
  
•    Process	
  id	
  
Reason	
  for	
  GC	
  Run	
  
02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  GC_CONCURRENT	
  freed	
  
                                                   GC_CONCURRENT	
  
1536K,	
  17%	
  free	
  10790K/12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  




Possible	
  reasons:	
  
•  GC_CONCURRENT	
  
•  GC_FOR_MALLOC/GC_FOR_ALLOC	
  
•  GC_EXTERNAL_ALLOC	
  
•  GC_HPROF_DUMP_HEAP	
  
•  GC_EXPLICIT	
  
 	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Amount	
  of	
  memory	
  reclaimed	
  
   02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  GC_CONCURRENT	
  freed	
  
                                                                         freed	
  
   1536K,	
  17%	
  free	
  10790K/12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  
   1536K,	
  	
  



                                      Heap	
  sta@s@cs	
  
	
   02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  GC_CONCURRENT	
  freed	
  
     1536K,	
  17%	
  free	
  10790K/12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  
            17%	
  free	
  10790K/12856K	
  

•  Percentage	
  of	
  free	
  heap	
  memory	
  aber	
  the	
  GC	
  run	
  
•  Size	
  of	
  objects	
  alive/Total	
  heap	
  size	
  	
  

                                           Pause	
  @me	
  
	
   02-­‐25	
  11:12:59.321:	
  D/dalvikvm(7757):	
  GC_CONCURRENT	
  freed	
  
     1536K,	
  17%	
  free	
  10790K/12856K,	
  paused	
  3ms+3ms,	
  total	
  21ms	
  
                                                        paused	
  3ms+3ms,	
  total	
  21ms	
  
Bitmaps	
  –	
  what	
  has	
  changed?	
  
                          Before	
  Honeycomb	
  




                                                    Dalvik	
  Heap	
  



                                                      Na@ve	
  
                                                      Memory	
  

      Pixel	
  Data	
  
Bitmaps	
  –	
  what	
  has	
  changed?	
  
            Aber	
  Honeycomb	
  



                  Pixel	
  Data	
  

                                      Dalvik	
  Heap	
  



                                        Na@ve	
  
                                        Memory	
  
Bitmaps	
  –	
  what	
  has	
  changed?	
  




                   Before	
                                                    Aber	
  
                                           Bitmap	
  pixel	
  data	
  storage	
  
Na@ve	
  memory	
  
•    Freed	
  via	
  –recycle	
  or	
  finalizer	
  
                                                                    Dalvik	
  Heap	
  
                                                                    •    Freed	
  synchronously	
  by	
  GC	
  
•    Hard	
  to	
  debug	
  
•    Full	
  GC	
  (stop-­‐the-­‐world)	
                           •    Easy	
  to	
  debug	
  
                                                                    •    Concurrent	
  and	
  par@al	
  GCs	
  
Profit?	
  

•  When	
  pixel	
  data	
  is	
  stored	
  in	
  Dalvik	
  heap	
  
   it	
  is	
  much	
  easier	
  to	
  debug	
  memory	
  usage	
  
   as	
  everything	
  is	
  in	
  one	
  place	
  
•  Pixel	
  data	
  in	
  pre-­‐Honeycomb	
  was	
  freed	
  
   by	
  recycle()	
  or	
  finalizer,	
  now	
  freed	
  
   syncronously	
  by	
  GC	
  
•  GCs	
  of	
  pixel	
  data	
  are	
  now	
  concurrent	
  and	
  
   par4al	
  –	
  pause	
  4mes	
  are	
  smaller	
  
Alloca@on	
  tracker	
  (Monitor)	
  
•  Info	
  about	
  	
  object	
  alloca@ons	
  in	
  a	
  specific	
  @me	
  period	
  	
  
Eclipse	
  Memory	
  Analyzer	
  Tool	
  
Heap	
  Dump	
  
•  Is	
  a	
  snapshot	
  of	
  all	
  “living”	
  objects	
  at	
  a	
  given	
  
   point	
  in	
  @me	
  
•  Contains	
  info	
  about	
  which	
  objects	
  are	
  GC	
  
   roots	
  (will	
  not	
  be	
  reclaimed	
  if	
  there	
  are	
  no	
  
   refs	
  to	
  them).	
  
•  Does	
  not	
  contain	
  info	
  about	
  na@ve	
  objects	
  
   (pre-­‐Honeycomb	
  Bitmaps	
  e.g.)	
  
Object	
  size	
  
•  Shallow	
  size	
  of	
  an	
  object	
  –	
  amount	
  of	
  memory	
  
   allocated	
  to	
  store	
  the	
  object	
  itself,	
  not	
  taking	
  
   into	
  account	
  the	
  referenced	
  object.	
  (Sum	
  of	
  
   size	
  of	
  the	
  object	
  header	
  and	
  the	
  fields)	
  
                                   Shallow	
  size	
  

         String	
  1	
                              String	
  2	
  
Shallow	
  object	
  size	
  -­‐	
  example	
  
public	
  final	
  class	
  String	
  {	
  //	
  8	
  Bytes	
  header	
  
       	
  private	
  char	
  value[];	
  	
  //	
  4	
  Bytes	
  
       	
  private	
  int	
  offset;	
  //	
  4	
  Bytes	
  
       	
  private	
  int	
  count;	
  //	
  4	
  Bytes	
  
       	
  private	
  int	
  hash	
  =	
  0;	
  //	
  4	
  Bytes	
  
…}	
  
	
  
“Shallow	
  size”	
  of	
  a	
  String	
  ==	
  24	
  Bytes	
  
(32	
  bit	
  Sun	
  JDK)	
  
	
  
Retained	
  set	
  
•  Retained	
  set	
  of	
  object	
  X	
                                                         Object	
  
                                                                                                    X	
  
     –  The	
  set	
  of	
  objects	
  that	
  would	
  be	
  
        garbage	
  collected,	
  if	
  object	
  X	
  is	
  
        deleted	
  
     –  The	
  retained	
  size	
  of	
  an	
  object	
  X	
     Retained	
  set	
  of	
  X	
  
        is	
  equal	
  to	
  the	
  shallow	
  size	
  of	
  
        the	
  “Retained	
  sets”	
  of	
  X	
  
Genera@ng	
  a	
  heap	
  dump	
  file	
  




  •  Dump	
  HPROF	
  file	
  (DDMS	
  or	
  programma@cally)*	
  
  •  Convert	
  	
  (Not	
  needed	
  in	
  Eclipse	
  DDMS)	
  
  hprof-­‐conv	
  dump.hprof	
  dump-­‐conv.hprof	
  
  •  Open	
  the	
  file	
  with	
  Eclipse	
  MAT	
  

*android.os.dumpHprofData(String	
  filename)	
  
Ini@al	
  pie	
  chart	
  view	
  
•  Shows	
  the	
  biggest	
  objects	
  be	
  their	
  retained	
  
   size	
  
Histogram	
  view	
  
Number	
  of	
  instances	
  of	
  each	
  class	
  and	
  their	
  shallow	
  size	
  
Histogram	
  view	
  
                           Oben	
  not	
  very	
  useful.	
  Why?	
  
Class	
  name	
                         Number	
  of	
  objects	
              Shallow	
  size	
  in	
  bytes	
  

char[]	
                                                        9	
  597	
                          555	
  496	
  

Java.lang.String	
                                           10	
  799	
                            259	
  176	
  



           How	
  many	
  char[]	
  are	
  
           caused	
  by	
  String	
  
           instances?	
  
Dominator	
  tree	
  example	
  
An	
  object	
  A	
  dominates	
  on	
  an	
  object	
  B	
  if	
  all	
  the	
  
paths	
  to	
  object	
  B	
  pass	
  through	
  object	
  A.	
  




                                       1.	
  Note	
  that	
  A,	
  B	
  and	
  C	
  are	
  dominated	
  by	
  a	
  
                                       "virtual"	
  root	
  object.	
  
                                       	
  
                                       2.	
  Note	
  that	
  the	
  dominator	
  rela@onship	
  
                                       is	
  transi4ve;	
  C	
  dominates	
  E	
  which	
  dominates	
  G	
  
                                       therefore	
  C	
  also	
  dominates	
  G.	
  
Dominator	
  tree	
  view	
  
List	
  of	
  objects	
  by	
  their	
  retained	
  heap	
  
Memory	
  Leak	
  Demo	
  
Ques@ons?	
  




                Taras	
  Leskiv	
  
                leskiv.taras@gmail.com	
  
                linkedin.com/in/tarasleskiv	
  

More Related Content

Viewers also liked

Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in AndoidMonkop Inc
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in AndroidKeyhan Asghari
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_appsBin Shao
 
Tuning Android for low RAM
Tuning Android for low RAMTuning Android for low RAM
Tuning Android for low RAMChris Simmonds
 
So You Finally Got Your Job at GameDev. What's next?
So You Finally Got Your Job at GameDev. What's next?So You Finally Got Your Job at GameDev. What's next?
So You Finally Got Your Job at GameDev. What's next?Taras Leskiv
 
[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applicationsAiTi Education
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devicesDroidcon Berlin
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in AndroidOpersys inc.
 
Android Development - NOTE TAKING APP FROM SCRATCH
Android Development - NOTE TAKING APP FROM SCRATCHAndroid Development - NOTE TAKING APP FROM SCRATCH
Android Development - NOTE TAKING APP FROM SCRATCHKeith Levi Lumanog
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance TestingAnand Bagmar
 
Patterns of a “good” test automation framework
Patterns of a “good” test automation frameworkPatterns of a “good” test automation framework
Patterns of a “good” test automation frameworkAnand Bagmar
 
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)Anand Bagmar
 
Unty3D Awesome Assets - uTomate
Unty3D Awesome Assets - uTomateUnty3D Awesome Assets - uTomate
Unty3D Awesome Assets - uTomateTaras Leskiv
 
Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineAndrew Case
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
Forensic Memory Analysis of Android's Dalvik Virtual Machine
Forensic Memory Analysis of Android's Dalvik Virtual MachineForensic Memory Analysis of Android's Dalvik Virtual Machine
Forensic Memory Analysis of Android's Dalvik Virtual MachineSource Conference
 
Game Center iOS + Unity3d
Game Center iOS + Unity3dGame Center iOS + Unity3d
Game Center iOS + Unity3dTaras Leskiv
 

Viewers also liked (20)

Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in Android
 
Memory in Android
Memory in AndroidMemory in Android
Memory in Android
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_apps
 
Tuning Android for low RAM
Tuning Android for low RAMTuning Android for low RAM
Tuning Android for low RAM
 
So You Finally Got Your Job at GameDev. What's next?
So You Finally Got Your Job at GameDev. What's next?So You Finally Got Your Job at GameDev. What's next?
So You Finally Got Your Job at GameDev. What's next?
 
[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devices
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in Android
 
Android Development - NOTE TAKING APP FROM SCRATCH
Android Development - NOTE TAKING APP FROM SCRATCHAndroid Development - NOTE TAKING APP FROM SCRATCH
Android Development - NOTE TAKING APP FROM SCRATCH
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance Testing
 
Patterns of a “good” test automation framework
Patterns of a “good” test automation frameworkPatterns of a “good” test automation framework
Patterns of a “good” test automation framework
 
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
 
Android seminar ppt
Android seminar pptAndroid seminar ppt
Android seminar ppt
 
Unty3D Awesome Assets - uTomate
Unty3D Awesome Assets - uTomateUnty3D Awesome Assets - uTomate
Unty3D Awesome Assets - uTomate
 
Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual Machine
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
Forensic Memory Analysis of Android's Dalvik Virtual Machine
Forensic Memory Analysis of Android's Dalvik Virtual MachineForensic Memory Analysis of Android's Dalvik Virtual Machine
Forensic Memory Analysis of Android's Dalvik Virtual Machine
 
Game Center iOS + Unity3d
Game Center iOS + Unity3dGame Center iOS + Unity3d
Game Center iOS + Unity3d
 

Similar to Android memory fundamentals

Taming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteTaming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteScyllaDB
 
Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Benoit Perroud
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Marcos García
 
Fengqi.asia Cloud advantages
Fengqi.asia Cloud advantagesFengqi.asia Cloud advantages
Fengqi.asia Cloud advantagesAndrew Wong
 
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...peknap
 
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~Unity Technologies Japan K.K.
 
Heapoff memory wtf
Heapoff memory wtfHeapoff memory wtf
Heapoff memory wtfOlivier Lamy
 
Garbage collection Overview
Garbage collection OverviewGarbage collection Overview
Garbage collection OverviewEugenio Lentini
 
Continguous Memory Allocator in the Linux Kernel
Continguous Memory Allocator in the Linux KernelContinguous Memory Allocator in the Linux Kernel
Continguous Memory Allocator in the Linux KernelKernel TLV
 
#GeodeSummit - Off-Heap Storage Current and Future Design
#GeodeSummit - Off-Heap Storage Current and Future Design#GeodeSummit - Off-Heap Storage Current and Future Design
#GeodeSummit - Off-Heap Storage Current and Future DesignPivotalOpenSourceHub
 
39 virtual memory
39 virtual memory39 virtual memory
39 virtual memorymyrajendra
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimizationRajan Jethva
 
Google App Engine, Groovy and Gaelyk presentation at the Paris JUG
Google App Engine, Groovy and Gaelyk presentation at the Paris JUGGoogle App Engine, Groovy and Gaelyk presentation at the Paris JUG
Google App Engine, Groovy and Gaelyk presentation at the Paris JUGGuillaume Laforge
 
Dsmp Whitepaper Release 3
Dsmp Whitepaper Release 3Dsmp Whitepaper Release 3
Dsmp Whitepaper Release 3gelfstrom
 
Share and Share Alike
Share and Share AlikeShare and Share Alike
Share and Share Alikeawebneck
 

Similar to Android memory fundamentals (20)

Taming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteTaming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust Rewrite
 
Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)
 
Ch5
Ch5Ch5
Ch5
 
Memory management
Memory managementMemory management
Memory management
 
Fengqi.asia Cloud advantages
Fengqi.asia Cloud advantagesFengqi.asia Cloud advantages
Fengqi.asia Cloud advantages
 
Massively Parallel Architectures
Massively Parallel ArchitecturesMassively Parallel Architectures
Massively Parallel Architectures
 
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...
Controlling Memory Footprint at All Layers: Linux Kernel, Applications, Libra...
 
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
 
Memory Unit
Memory UnitMemory Unit
Memory Unit
 
Apache Geode Offheap Storage
Apache Geode Offheap StorageApache Geode Offheap Storage
Apache Geode Offheap Storage
 
Heapoff memory wtf
Heapoff memory wtfHeapoff memory wtf
Heapoff memory wtf
 
Garbage collection Overview
Garbage collection OverviewGarbage collection Overview
Garbage collection Overview
 
Continguous Memory Allocator in the Linux Kernel
Continguous Memory Allocator in the Linux KernelContinguous Memory Allocator in the Linux Kernel
Continguous Memory Allocator in the Linux Kernel
 
#GeodeSummit - Off-Heap Storage Current and Future Design
#GeodeSummit - Off-Heap Storage Current and Future Design#GeodeSummit - Off-Heap Storage Current and Future Design
#GeodeSummit - Off-Heap Storage Current and Future Design
 
39 virtual memory
39 virtual memory39 virtual memory
39 virtual memory
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimization
 
Google App Engine, Groovy and Gaelyk presentation at the Paris JUG
Google App Engine, Groovy and Gaelyk presentation at the Paris JUGGoogle App Engine, Groovy and Gaelyk presentation at the Paris JUG
Google App Engine, Groovy and Gaelyk presentation at the Paris JUG
 
Dsmp Whitepaper Release 3
Dsmp Whitepaper Release 3Dsmp Whitepaper Release 3
Dsmp Whitepaper Release 3
 
Share and Share Alike
Share and Share AlikeShare and Share Alike
Share and Share Alike
 

Recently uploaded

Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
20200723_insight_release_plan
20200723_insight_release_plan20200723_insight_release_plan
20200723_insight_release_planJamie (Taka) Wang
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxYounusS2
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 

Recently uploaded (20)

Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
20200723_insight_release_plan
20200723_insight_release_plan20200723_insight_release_plan
20200723_insight_release_plan
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptx
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 

Android memory fundamentals

  • 1. Memory  Management  Fundamentals   for  Android  apps  
  • 2. Agenda   1.  Memory  usage  model   –  Constraints     –  Zygote,  Dalvik  and  GC   2.  Tools  for  memory  diagnos@cs   –  adb  shell  procrank   –  lava.lang.Run@me   –  Log  messages   –  Alloca@on  tracker   –  Eclipse  MAT    
  • 3. We’ve  grown  bigger  and  stronger   12x  RAM     T-­‐Mobile  G1  (2008)   Nexus  4   (2012)   192  MB   2  GB  
  • 4. So  why  should  we  care  about  the   memory?   •  Heap  size  is  limited  and  device  dependent   •  Screen  size  has  grown  drama@cally  -­‐  Bitmaps   •  System  libraries  occupy  significant  amount  of   storage   •  The  more  memory  we  use,  the  more  work  GC   has,  the  more  work  GC  has  the  bigger  pause   @me  will  be.   •  BaWery  life  
  • 6. Dalvik  VM  .dex  format  
  • 7. Respect  the  balance!   Cache  as   much  useful   Use  as  liWle   data  as  you   memory  as   can   you  can   Why?   Why?   I  can  do   I  will  kill  your  process  as   mul@tasking  and  I   soon  as  I  don’t  have   want  smooth  UX   memory  for  other  apps   and  your  app  uses  lots  of   when  switching   memory   between  apps  
  • 8. Mark-­‐and-­‐sweep  GC   Larger  heap  =  larger  pause  @me  =   poor  performance  
  • 9. Mark-­‐and-­‐sweep  GC   GC   Roots   Phase  1   Before  GC  
  • 10. Mark-­‐and-­‐sweep  GC   GC   Phase  2   Roots   Marking  complete     -­‐  Marked  object   -­‐  Garbage   Mark:  star@ng  from  roots,  mark  all  reachable  objects  by  using  a  depth-­‐first-­‐search   pointer  traversal  
  • 11. Mark-­‐and-­‐sweep  GC   GC   Phase  3   Roots   Sweep  complete     -­‐  Marked  object   Sweep:  scan  the  heap  from  the  beginning  to  the  end  and  reclaim  the   unmarked  objects  (and  unmark  the  marked  objects).  
  • 12. GC  Improvements   Before   Aber   Garbage  collector   •  Stop-­‐the-­‐world   •  Advantage  of  mul@core  support   •  Full  heap  collec@on   •  Mostly  concurrent   •  Large  pause  @mes   •  Par@al  collec@ons   •  Smaller  pause  @mes  
  • 13. GC  Improvements   Aber   Before   •  Stop-­‐the-­‐world  –   all  app  threads  are   stopped   •  Full  heap  collec@on   •  Large  pause  @mes   oben  >  100ms   •  Ini4al  mark  -­‐  stop-­‐the-­‐world   •  Mark  -­‐  concurrent   •  Remark  –  stop-­‐the-­‐world   •  Sweep  -­‐  concurrent  
  • 14. Healthy  memory  usage  paWern   Maximum   heap*  size   Allocated     GC  Run   memory   Garbage   Memory   Usage   Time   *  Maximum  amount  of  memory  our  app  is  allowed  to  use  
  • 15. Edge  case   Maximum   heap*  size   OutOfMemoryError   Allocated     GC  Run   memory   Garbage   Memory   Usage   Time   *  Maximum  amount  of  memory  our  app  is  allowed  to  use  
  • 16. Are  we  leaking  memory?   Maximum  heap*  size   Allocated     GC  Run   memory   Garbage   Amount  of  memory   leaking   Memory   Usage   Memory  leak   Time   *  Maximum  amount  of  memory  our  app  is  allowed  to  use  
  • 17. Maximum  heap  size   So  how  much  memory  can  we  actually  use?     1.  ActivityManager.getMemoryClass()  –    device  dependent  –   always  constant   2.  Runtime.getRuntime().maxMemory()  –    can  be  changed  on   rooted  devices,  is  slightly  larger         T-­‐Mobile  G1  –  16  MB   Nexus  One  –  32  MB   Nexus  7  –  64  MB    
  • 18. Memory  intensive  apps   What  if  it  is  not  enough?  Image  editor?  Video   editor?  3D  game?     <application    android:largeHeap=“true”   </application>     Use  only  if  you  are  sure  you  need  this  extra   memory.     ActivityManager.getLargeMemoryClass()    
  • 20. Target  –  Honeycomb  Gallery  App   YOUR_SDK_LOCATIONsamplesandroid-­‐XXHoneycombGallery  
  • 21. Tools  to  diagnose  memory  usage   1.  adb  shell  procrank   2.  java.lang.Run@me   3.  Log  messages   4.  Alloca@on  tracker  and  heap  updates   5.  Heap  dumps  and  Eclipse  Memory  Analyzer   Tool  (MAT)  
  • 22. procrank  u@lity   Applica4on:  answers  a  ques@on  how   much  memory  are  we  actually  using.  
  • 23. procrank   Lists  of  all  processes  on  the  device  and  memory   they  are  using  (sorted  desc.).     adb  shell  procrank  (requires  root  access)     Uss  –  Unique  set  size  –  rough  memory  amount   the  system  would  reclaim  if  it  kills  the  process.  
  • 24. Java.lang.Run@me  methods   •  freeMemory()   •  totalMemory()   Applica4on:     •  observing  general  applica@on  memory  usage   paWern  at  run@me   •  provides  basic  understanding  of  memory  usage   behavior  
  • 25.              Observing  memory  state  changes   in  LogCat   new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(5000); } catch (InterruptedException e) { // do nothing } reportMemoryUsage(); } } }, “MemoryUsageReporter").start();  
  • 26.   Gives  a  general  idea  about  memory   changes  at  run@me   RAM  USAGE  free:  1.96MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  1.95MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  1.71MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  1.71MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  4.62MB,  total:  17.35MB,  max  :  64.00   RAM  USAGE  free:  4.62MB,  total:  17.35MB,  max  :  64.00   RAM  USAGE  free:  1.95MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  1.95MB,  total:  14.68MB,  max  :  64.00   RAM  USAGE  free:  1.95MB,  total:  14.68MB,  max  :  64.00    
  • 27. Interpre@ng  LogCat  messages   02-­‐25  11:12:59.321:  D/dalvikvm(7757):   GC_CONCURRENT  freed  1536K,  17%  free  10790K/ 12856K,  paused  3ms+3ms,  total  21ms  
  • 28. General  informa@on   02-­‐25  11:12:59.321:  D/dalvikvm(7757):   GC_CONCURRENT  freed  1536K,  17%  free  10790K/ 12856K,  paused  3ms+3ms,  total  21ms   •  Timestamp   •  Logging  level   •  Log  tag   •  Process  id  
  • 29. Reason  for  GC  Run   02-­‐25  11:12:59.321:  D/dalvikvm(7757):  GC_CONCURRENT  freed   GC_CONCURRENT   1536K,  17%  free  10790K/12856K,  paused  3ms+3ms,  total  21ms   Possible  reasons:   •  GC_CONCURRENT   •  GC_FOR_MALLOC/GC_FOR_ALLOC   •  GC_EXTERNAL_ALLOC   •  GC_HPROF_DUMP_HEAP   •  GC_EXPLICIT  
  • 30.                          Amount  of  memory  reclaimed   02-­‐25  11:12:59.321:  D/dalvikvm(7757):  GC_CONCURRENT  freed   freed   1536K,  17%  free  10790K/12856K,  paused  3ms+3ms,  total  21ms   1536K,     Heap  sta@s@cs     02-­‐25  11:12:59.321:  D/dalvikvm(7757):  GC_CONCURRENT  freed   1536K,  17%  free  10790K/12856K,  paused  3ms+3ms,  total  21ms   17%  free  10790K/12856K   •  Percentage  of  free  heap  memory  aber  the  GC  run   •  Size  of  objects  alive/Total  heap  size     Pause  @me     02-­‐25  11:12:59.321:  D/dalvikvm(7757):  GC_CONCURRENT  freed   1536K,  17%  free  10790K/12856K,  paused  3ms+3ms,  total  21ms   paused  3ms+3ms,  total  21ms  
  • 31. Bitmaps  –  what  has  changed?   Before  Honeycomb   Dalvik  Heap   Na@ve   Memory   Pixel  Data  
  • 32. Bitmaps  –  what  has  changed?   Aber  Honeycomb   Pixel  Data   Dalvik  Heap   Na@ve   Memory  
  • 33. Bitmaps  –  what  has  changed?   Before   Aber   Bitmap  pixel  data  storage   Na@ve  memory   •  Freed  via  –recycle  or  finalizer   Dalvik  Heap   •  Freed  synchronously  by  GC   •  Hard  to  debug   •  Full  GC  (stop-­‐the-­‐world)   •  Easy  to  debug   •  Concurrent  and  par@al  GCs  
  • 34. Profit?   •  When  pixel  data  is  stored  in  Dalvik  heap   it  is  much  easier  to  debug  memory  usage   as  everything  is  in  one  place   •  Pixel  data  in  pre-­‐Honeycomb  was  freed   by  recycle()  or  finalizer,  now  freed   syncronously  by  GC   •  GCs  of  pixel  data  are  now  concurrent  and   par4al  –  pause  4mes  are  smaller  
  • 35. Alloca@on  tracker  (Monitor)   •  Info  about    object  alloca@ons  in  a  specific  @me  period    
  • 37. Heap  Dump   •  Is  a  snapshot  of  all  “living”  objects  at  a  given   point  in  @me   •  Contains  info  about  which  objects  are  GC   roots  (will  not  be  reclaimed  if  there  are  no   refs  to  them).   •  Does  not  contain  info  about  na@ve  objects   (pre-­‐Honeycomb  Bitmaps  e.g.)  
  • 38. Object  size   •  Shallow  size  of  an  object  –  amount  of  memory   allocated  to  store  the  object  itself,  not  taking   into  account  the  referenced  object.  (Sum  of   size  of  the  object  header  and  the  fields)   Shallow  size   String  1   String  2  
  • 39. Shallow  object  size  -­‐  example   public  final  class  String  {  //  8  Bytes  header    private  char  value[];    //  4  Bytes    private  int  offset;  //  4  Bytes    private  int  count;  //  4  Bytes    private  int  hash  =  0;  //  4  Bytes   …}     “Shallow  size”  of  a  String  ==  24  Bytes   (32  bit  Sun  JDK)    
  • 40. Retained  set   •  Retained  set  of  object  X   Object   X   –  The  set  of  objects  that  would  be   garbage  collected,  if  object  X  is   deleted   –  The  retained  size  of  an  object  X   Retained  set  of  X   is  equal  to  the  shallow  size  of   the  “Retained  sets”  of  X  
  • 41. Genera@ng  a  heap  dump  file   •  Dump  HPROF  file  (DDMS  or  programma@cally)*   •  Convert    (Not  needed  in  Eclipse  DDMS)   hprof-­‐conv  dump.hprof  dump-­‐conv.hprof   •  Open  the  file  with  Eclipse  MAT   *android.os.dumpHprofData(String  filename)  
  • 42. Ini@al  pie  chart  view   •  Shows  the  biggest  objects  be  their  retained   size  
  • 43. Histogram  view   Number  of  instances  of  each  class  and  their  shallow  size  
  • 44. Histogram  view   Oben  not  very  useful.  Why?   Class  name   Number  of  objects   Shallow  size  in  bytes   char[]   9  597   555  496   Java.lang.String   10  799   259  176   How  many  char[]  are   caused  by  String   instances?  
  • 45. Dominator  tree  example   An  object  A  dominates  on  an  object  B  if  all  the   paths  to  object  B  pass  through  object  A.   1.  Note  that  A,  B  and  C  are  dominated  by  a   "virtual"  root  object.     2.  Note  that  the  dominator  rela@onship   is  transi4ve;  C  dominates  E  which  dominates  G   therefore  C  also  dominates  G.  
  • 46. Dominator  tree  view   List  of  objects  by  their  retained  heap  
  • 48. Ques@ons?   Taras  Leskiv   leskiv.taras@gmail.com   linkedin.com/in/tarasleskiv