4. Under the hoodâŚ
⢠Since Android is built on top of a
Linux Kernel, we should know a little
bit about memory management on
Linux âŚ
⢠Other key topics that helps a lot:
â Virtual Memory
â Android Activity Lifecycle
â Garbage Collection
â Memory Heap
6. Linux Kernel
⢠Linux 2.6 + Google architecture
changes.
⢠Android core functionality is based on
top of Linux
â Hardware interface & drivers
â Memory Management
â Process Management
â Networking
â Security
â Etc.
8. Android Runtime
⢠Dalvik Virtual Machine
â Like a special Java VM
â Optimized for mobile world
â Not .class -> .dex (bulit from a .class)
â Multiple instances of the VM running
⢠Core Libraries
â Most of the functionalities of the Java SE
libraries
10. Virtual Memory
⢠Maps process memory
addresses (virtual) into
physical addresses.
⢠Hardware: Address
translation inside CPU
(called MMU)
⢠Software: Extend physical
memory size
11. Virtual Memory - Key Benefits
⢠Avoid process to handle a shared
space.
⢠More security & isolation
⢠More memory available
⢠Easier programming / hidden
fragmentation
12. Concepts
⢠Swap Space
â Extend physical (full) memory with HD
⢠Paging
â Uses HD to store & retrieve âpagesâ of
memory.
â Allow non-contiguous address space for
process
â One of the most important part of typical
Virtual Memory implementation
⢠Shared Memory
⢠Heap
15. Android Way
⢠Memory:
â No Swap space, Paging
â Memory mapping
⢠Shared Memory
â Framework code & resources
â Intercommunication (processes)
â Intensively used
16. Android Way
⢠New drivers:
â ASHMEM (re-implemented)
â Low Memory Killer (handle OOM
situations)
⢠Empty Process
â When a process is terminated, not all
memory is released.
â Reduces response time when user
access same process.
17. Garbage Collection
1. Pre Gingerbread:
â GC âstops the worldâ
â Full heap collection
â Pause time often > 100ms
2. Gingerbread and beyond:
â Concurrent (mostly)
â Partial Collections
â Pause time usually < 5ms
18. Garbage Collection - MsgTypes
⢠GC_CONCURRENT: Occurs when heap is growing (to
avoid enlarge heap in time)
⢠GC_EXPLICIT: Triggered when an application calls System.gc(). Donât use
it!
⢠GC_FOR_MALLOC: Triggered when the heap is full and the application
needs more memory. (stops app)
⢠GC_HPROF_DUMP_HEAP: Triggered when an HPROF file is created for
memory analysis
⢠GC_BEFORE_OOM: (Undocumented) Itâs supposed to be triggered when
dalvik heap usage is over 90%
19. Android App Memory
⢠Dalvik heap
â Defines logical heap size
â Memory can grow to a defined limit
(defined by the system)
â One single virtual memory range
â Physically non-contiguous (analyzed on
GC)
⢠Logical size is different than Physical
size
⢠Hard to know exactly how much RAM
your process are using
21. Proportional Set Size (PSS)
⢠PSS is considered by Android as your
physical footprint
⢠Example of Dalvik Heap usage:
â 20MB of (Private)
â 12MB of Shared (between 4 process)
â PSS = 20 + (12/4) = 23
23. Private RAM
⢠Private (Dirty and Clean) is memory
used by the App.
⢠All heap allocations (Dalvik + Native)
⢠Memory that will be available if your
process is destroyed.
⢠Canât be paged into storage
25. Low Memory Killer (Linux)
⢠Look for âbadâ process (heuristics):
â High memory consuming is bad
â Long running process are good
â Process with a lot of child process are
bad
â Root processes are good (3% off)
26. Low Memory Killer (Android)
5 - Empty Process
4 - Background Process
3 - Started Services Process
2 - Visible Process
1 - Active Process Critical Priority
High Priority
Low Priority
27. Low Memory Killer (Android)
Threshold varies based on RAM size.
aded during booting time from init.rc file)
Memory Pages
(4KB each)
28. 3 Memory Tips 4 Apps
1. Use Services in the right way
â Only one process should take care of UI
â Take care about dependencies
2. Release memory when
â Your UI becomes hidden
â Memory becomes tight
(ComponentCallbacks)
3. Use the right Bitmaps for each screen
resolution
29. Services
⢠Application component without UI.
⢠Can be used to perform long-running
operations in background.
⢠Inter-process communication
⢠Provide a client-server model to bind
with
31. Services Started
> startService();
â˘Can run indefinitely
â˘Even if the activity who
started it is destroyed
â˘Once it is finished, the service
should stop itself
32. Services Bound
> bindService();
â˘Client / Server interface to:
⢠Request service
⢠Get results
⢠IPC
â˘Bind by one
â˘Is destroyed only when all of
them unbind
34. Bitmaps
⢠Load the bitmap that your app
needs!
â Scale down image to your resolution
â Or you need more than 1 resolution per
image
⢠API_level <= 10:
35. Bitmaps
⢠Load the bitmap that your app
needs!
â Scale down image to your resolution
â Or you need more than 1 resolution per
image
⢠API_level >= 11: (Honeycomb &
higher)
36. Tools & logs
â Logs:
⢠Dalvik Log Messages: All Garbage Collection logs
⢠ART: Logged when GC are deemed slow:
â GC Pauses > 5ms
â GC duration > 100ms
â Explicit GCs
â Android Device Monitor for tracking
Allocations
â MAT: Eclipse Memory Analyzer Tool
â Monkop: Memory Footprints on real devices
⢠GC behavior
⢠RAM footprint
⢠Threads
⢠CPU / Network and others
Android is a linux-based embedded operating system for mobile devices such as smart
phones and tablets. It is open source. It supports many architectures like ARM, MIPS,
X86. It uses modified linux kernel 2.6. Linux Kernel type is monolithic. Even though
android uses linux kernel but it varies in some of the core components.
Surface Manager: It is used for compositing window manager with off-screen buffering. Off-screen buffering means you cant directly draw into the screen, but your drawings go to the off-screen buffer. There it is combined with other drawings and form the final screen the user will see. This off screen buffer is the reason behind the transparency of windows.
Media framework: Media framework provides different media codecs allowing the recording and playback of different media formats
SQLite: SQLite is the database engine used in android for data storage purposes
WebKit: It is the browser engine used to display HTML content
OpenGL: Used to render 2D or 3D graphics content to the screen
Dalvik Virtual Machine
It is a type of JVM used in android devices to run apps and is optimized for low processing power and low memory environments. Unlike the JVM, the Dalvik Virtual Machine doesnât run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides higher efficiency in low resource environments. The Dalvik VM allows multiple instance of Virtual machine to be created simultaneously providing security, isolation, memory management and threading support. It is developed by Dan Bornstein of Google.
Core Java Libraries
These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.
These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource management, voice call management etc. As a developer, you just consider these are some basic tools with which we are building our applications.
Important blocks of Application framework are:
Activity Manager: Manages the activity life cycle of applications
Content Providers: Manage the data sharing between applications
Telephony Manager: Manages all voice calls. We use telephony manager if we want to access voice calls in our application.
Location Manager: Location management, using GPS or cell tower
Resource Manager: Manage the various types of resources we use in our Application
Android does not offer swap space for memory, but it does use paging and memory-mapping (mmapping) to manage memory. This means that any memory you modifyâwhether by allocating new objects or touching mmapped pagesâremains resident in RAM and cannot be paged out. So the only way to completely release memory from your app is to release object references you may be holding, making the memory available to the garbage collector. That is with one exception: any files mmapped in without modification, such as code, can be paged out of RAM if the system wants to use that memory elsewhere.
Sharing Memory: In order to fit everything it needs in RAM, Android tries to share RAM pages across processes.
Android does not offer swap space for memory, but it does use paging and memory-mapping (mmapping) to manage memory. This means that any memory you modifyâwhether by allocating new objects or touching mmapped pagesâremains resident in RAM and cannot be paged out. So the only way to completely release memory from your app is to release object references you may be holding, making the memory available to the garbage collector. That is with one exception: any files mmapped in without modification, such as code, can be paged out of RAM if the system wants to use that memory elsewhere.
Sharing Memory: In order to fit everything it needs in RAM, Android tries to share RAM pages across processes.
Pre gingerbread: All app threads where paused when GC is working.
Post gingerbread concurrent GC was implemented (Non-stop)
https://sites.google.com/site/pyximanew/blog/androidunderstandingddmslogcatmemoryoutputmessages
GC_EXTERNAL_MALLOC: Used for externally allocated memory like bitmaps and NIO direct bytebuffers. This is only on pre-Honeycomb devices because from Honeycomb the external memory is allocated inside dalvik heap
It stores oom adj (out of memory adjust) values for each group of processes, oom adj
value ranges from -17 to 16. It also stores memory(minfree) thresholds for each group
of processes at which this group processes gets killed. All these oom adj and minfree
thresholds are stored in init.rc file. Kernel reads these minfree, oom adj values from
init.rc during booting time[13].
From table 3.1, low memory killer starts killing processes whose oom adj value > 15
when free memory falls down less than 32MB (8192*4KB). Similarly low memory killer
starts killing processes whose oom adj value > 14 when free memory falls down less than
28MB (7168*4KB) like that for all. Memory thresholds are varies based on RAM size. The
values in table 3.1 are taken from a android OS mobile,with RAM size as 512MB. These
static minfree values causes to many problems regarding responsive time of a process and
battery life time. More details on these problems explained in chapter 05.
 If you are going to split your app into multiple processes, only one process should be responsible for UI. Other processes should avoid any UI, as this will quickly increase the RAM required by the process (especially once you start loading bitmap assets and other resources). It may then be hard or impossible to reduce the memory usage once the UI is drawn.
Additionally, when running more than one process, it's more important than ever that you keep your code as lean as possible, because any unnecessary RAM overhead for common implementations are now replicated in each process. For example, if you are using enums (though you should not use enums), all of the RAM needed to create and initialize those constants is duplicated in each process, and any abstractions you have with adapters and temporaries or other overhead will likewise be replicated.
Another concern with multiple processes is the dependencies that exist between them. For example, if your app has a content provider that you have running in the default process which also hosts your UI, then code in a background process that uses that content provider will also require that your UI process remain in RAM. If your goal is to have a background process that can run independently of a heavy-weight UI process, it can't have dependencies on content providers or services that execute in the UI process.
https://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
https://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform inter-process communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
https://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform inter-process communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
https://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform inter-process communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
When the user navigates to a different app and your UI is no longer visible, you should release any resources that are used by only your UI. Releasing UI resources at this time can significantly increase the system's capacity for cached processes, which has a direct impact on the quality of the user experience.
To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.
Notice that your app receives the onTrimMemory() callback with TRIM_MEMORY_UI_HIDDEN only when all the UI components of your app process become hidden from the user. This is distinct from the onStop() callback, which is called when an Activity instance becomes hidden, which occurs even when the user moves to another activity in your app. So although you should implement onStop() to release activity resources such as a network connection or to unregister broadcast receivers, you usually should not release your UI resources until you receive onTrimMemory(TRIM_MEMORY_UI_HIDDEN). This ensures that if the user navigates back from another activity in your app, your UI resources are still available to resume the activity quickly.