Android Memory Management

Source: Internet
Author: User

Introduction: Android is a Linux-based operating system for mobile terminals. To meet its special needs as a mobile platform operating system, Google made a special design and optimization for it, so that the application is closed but not exited, the operating system recycles the processes. In the Application
In terms of framework and Linux kernel, process-specific process is used to analyze the process resource recycling mechanism in the Android operating system. Readers can further understand the lifecycle of Android applications from this article, so as to build applications more rationally and efficiently.
Running Environment of Android app
Android is an operating system for mobile terminals based on the Linux kernel. To adapt to its special needs as a mobile platform operating system, Google made a special design and optimization for it, making its process scheduling and resource management significantly different from that of Linux on other platforms. It mainly includes the following layers:
1. Application Framework
The application framework separates the entire operating system into two parts. For application developers, all apps run on the application framework, and do not need to care about the underlying system. The application framework layer provides a wide range of application programming interfaces for application developers, such as activity manager, content provider, and notification.
Manager, as well as various Window widget resources. In the application framework layer, activity is the most basic component of an app. Generally, each activity corresponds to a view (or screen) on the screen. An app can have one or more activities. The application is packaged into A. APK file, which is interpreted and executed by Dalvik VM.
2. Dalvik VM
The Dalvik virtual machine uses the register architecture instead of the JVM stack structure. The. Class file compiled by the Java program cannot be interpreted and executed in Dalvik. Therefore, Google provides a DX tool to convert. class files into A. Dex format that can be recognized by dalivk. The specific Dalvik VM details are not the focus of this article, and will not be discussed below.
3. Linux Kernel
As described above, all apps are written in Java code and interpreted and executed in Dalvik VM. In the Android operating system, each instance of each Dalvik VM corresponds to a process in the Linux kernel. You can use the ADB shell tool to view the current process in the system. As shown in, the list of processes in the kernel after android2.3.3 is started

Android memory reclaim Principle
The following describes the Resource Management Mechanism of the Android operating system at the application framework and Linux kernel levels.
Android uses a special resource management mechanism because it was designed for mobile terminals at the beginning. All available memory is limited to system ram, and corresponding optimization solutions must be designed for this limitation. When the Android Application exits, it does not clean up the memory occupied by it, and the Linux kernel process also exists accordingly. The so-called "exit but not close ". This allows the user to get a response immediately when calling the program. When the system memory is insufficient, the system will activate the memory recovery process. In order not to affect the user experience (such as killing the current active process) due to memory recycle, Android sets the default five recycle priorities based on the components running in the process and their statuses:
Importance_foreground:
Importance_visible:
Importance_service:
Importance_background:
Importance_empty:
The recovery sequence of these priorities is empty process, background process, service process, visible process, and foreground process. For details about the partitioning principles, see http://developer.android.com/guide/components/processes-and-threads.html.
Activitymanagerservice centrally manages the memory resource allocation of all processes. All processes must call the activitymanagerservice object before applying for or releasing the memory. After obtaining the "License", the activitymanagerservice can perform the next operation ". Several important member methods involved in memory reclaim in activitymanagerservice are as follows: trimapplications (), updateoomadjlocked (), and activityidleinternal (). These member methods are mainly responsible
Android uses the default memory recycle mechanism. If the memory recycle mechanism in the Linux kernel is not disabled, the default recycle mechanism is skipped.
Default Recycle Process
Memory recovery in the Android operating system can be divided into two levels: Default memory recovery and kernel-level memory recovery. This chapter mainly studies the default memory recovery mechanism, the memory recovery mechanism at the Linux kernel level will be introduced in the next section. For all the code in this chapter, see activitymanagerservice. java.
Recycling action entry: activityidleinternal ()
Memory recovery trigger points in the Android system can be roughly divided into three situations. First, the user program calls startactivity () to overwrite the activity of the current activity. Second, the user presses the back key to exit the current application. Third, start a new application. The final function interface that can trigger memory reclaim is activityidleinternal (). When activitymanagerservice receives the asynchronous message idle_timeout_msg or idle_now_msg, activityidleinternal () is called. The Code is as follows:
Listing 1. idle_now_msg Processing Method

Case idle_now_msg :{
Ibinder token = (ibinder) msg. OBJ;
Activityidle (token, null );
}
Break;
Listing 2. idle_timeout_msg Processing Method
1
Case idle_timeout_msg :{
If (mdiddexopt ){
Mdiddexopt = false;
Message nmsg = mhandler. obtainmessage (idle_timeout_msg );
Nmsg. OBJ = msg. OBJ;
Mhandler. sendmessagedelayed (nmsg, idle_timeout );
Return;
}
Ibinder token = (ibinder) msg. OBJ;
Slog. W (TAG, "activity idle timeout for" + token );
Activityidleinternal (token, true, null );
}
Break;
Idle_now_msg is triggered by events such as activity switching and Activiy focus change. idle_timeout_msg is triggered when activity startup times out. Generally, this timeout time is set to 10 s, if an activity is not started successfully within 10 s, the asynchronous message idle_timeout_msg will be sent to recycle resources. The main task of activityidleinternal () is to change the status information of the activity in the system and add it to different status lists. Its main work is as follows:
Call the scheduleappgcslocked () method to notify all ongoing tasks of garbage collection. Scheduleappgcslocked () is used to schedule the garbage collect of JVM and reclaim part of the memory space. Here, it only notifies each process of spam check and scheduling collection time, rather than synchronous collection. Then, retrieve all the content in the mstoppingactivities and mfinishigactivities lists and store them in temporary variables. The two lists store activity objects in the stop and finishi statuses respectively. For
Stop list. If the finish status of the activity is true, you can determine whether to stop the activity immediately. If you want to stop the activity immediately, call destroyactivitylocked () to notify the target process to call the ondestroy () method. Otherwise, call resumetopactivity () to run the next activity. If the finish status is false, stopactivitylocked () is called to notify the client process to stop the activity. This usually happens after startactivity () is called. For
List, directly call destroyactivitylocked () to notify the customer process to destroy the target activity.
Here, the destroyactivitylocked and other functions do not actually change the memory usage, but change its status to "allow recycling". The actual recycling is in the trimapplications () function to be called below.
Recycling process function trimapplications ()
The structure of the trimapplications () function is as follows:
Listing 3. trimapplications Function

Private final void trimapplications (){
Synchronized (this ){
// First remove any unused application processes whose package
// Has been removed.
For (I = mremovedprocesses. Size ()-1; I> = 0; I --){
(1) // kill process;
}
If (! Updateoomadjlocked ()){
(2) // do something default
}
// Finally, if there are too then activities now running, try
// Finish as finished as we can to get back down to the limit.
(3) do something
}
}
The positions of the three serial numbers in listing 3 are responsible for the following:
(1) After the program is executed to trimapplications (), first check the processes in the mremovedprocesses list. The mremovedprocesses list mainly contains the crash process, the process that does not respond within 5 seconds and is selected by the user for forced shutdown, and the process that the Application Development calls killbackgroundprocess to kill. Call process. killprocess to kill all such processes.
(2) Call the updateoomadjlocked () function. If the response is successful, the Linux kernel supports the setoomadj () interface. updateoomadjlocked will modify the value of the adj and notify the Linux kernel, the kernel dynamically manages process resources (lowmemorykiller and oom_killer) based on the embedded values and memory usage ). If updateoomadjlocked () returns false, it indicates that the current system does not support the setoomadj () interface, and the default resource is recycled locally.
(3) At last, if too many activities are still running, recycle unnecessary activities. Most code of trimapplications () processes the default resource reclaim when oom_killer does not exist, and faces the default recycle process (that is, the location marked (2) in the code list) for further analysis. The recycling process can be roughly described as follows.
Step 1: obtain all currently running processes mlruprocesses. The sorting rules in mlruprocesses are based on the recent usage time. Count the processes that cannot be shut down in mlruprocesses. The processes that cannot be shut down include the processes that run the service and the processes that run the broadcast explorer. See the following code.
Listing 4. Count processes that cannot be disabled

If (App. Persistent | app. Services. Size ()! = 0
| App. cursponer! = NULL
| App. persistentactivities> 0 ){
// Don't count processes holding services against our
// Maximum process count.
Numserviceprocs ++;
}
Step 2: set the current maximum number of processes to curmaxprocs = curmaxprocs + numserviceprocs (that is, the sum of the default maximum number of processes and the number of processes running the service), if the current number of processes is mremovedprocesses. if the size () value is greater than this value, all processes that are currently running are traversed to kill qualified processes and release the memory. For the cleaning process, see listing 5 (some code is omitted ). From the code in listing 5, we can see that the process is killed by the following conditions:
● Non-persistent process, that is, non-system process;
● The process must be empty, that is, no activity exists in the process. If the active process is killed, it is possible to close the program in use or increase the latency of application recovery, thus affecting the user experience;
● No broadcast receiver is required. Generally, running a broadcast receiver is waiting for an event. You do not want this program to be forcibly disabled by the system;
● The number of services in a process must be 0. A service process is likely to provide certain services for one or more programs, such as the GPS positioning service. Killing such processes will make other processes unable to serve normally.
The preceding conditions are indispensable.
Listing 5. Cleaning Process

If (! App. Persistent & App. Activities. Size () = 0
& App. cursponer = NULL & App. Services. Size () = 0 ){
If (App. PID> 0 & App. PID! = My_pid ){
Process. killprocess (App. PID );
} Else {
Try {
App. thread. scheduleexit ();
} Catch (exception e ){
// Ignore exceptions.
}
}
// Todo: For now we assume the application is not buggy
// Or edevil, And will quit as a result of our request.
// Eventually we need to drive this off of the death
// Notification, and kill the process if it takes too long.
Cleanupapplicationrecordlocked (app, false, I );
I --;
}
Step 3: Check the currently running process again. If mremovedprocesses. Size () is still greater than curmaxprocs, the condition is relaxed and recycled again. For the judgment conditions, see code listing 6 (some code is omitted ). In the following code, when the value of the Boolean variable canquit is true, this process can be recycled. The value of canquit is divided into two steps. The first step is to assign values based on the attributes of the process. 1. It must be a non-persistent process, that is, a non-system process; 2. There must be no broadcast guest er; 3. The number of services in the process must be 0; 4. Persistent type
The number of activities is 0. The only difference between Step 2 and Step 2 is Article 4th. Here, the process is not required to be a null process, as long as there is no activity of the persistent type in the process (whether the activity is specified in the development stage ). When these conditions are met, check the attributes of each activity in the process. When all the activities in the process must meet three conditions: the activity status has been saved, the activity is currently invisible and has been stopped. At this time, killing the process will only reduce the loading speed of the next program call. The next time it starts, it will be restored to the State before it is closed, and will not cause a fatal impact on the user experience. Therefore, canquit
Set the bit to true. This situation is different from the recycling method in step 2. because the number of activities in the process is not 0, you need to execute destroyactivitylocked () to destroy each activity and finally kill the process.
Listing 6. Execute destroyactivitylocked () to destroy

Boolean canquit =! App. Persistent & App. cursister = NULL
& Amp; app. Services. Size () = 0
& Amp; app. persistentactivities = 0;
Int NUMA = app. Activities. Size ();
For (j = 0; j <NUMA & canquit; j ++ ){
Historyrecord r = (historyrecord) app. Activities. Get (j );
Canquit = (R. havestate |! R. statenotneeded)
&&! R. Visible & R. stopped;
}
If (canquit ){
// Finish all of the activities, and then the app itself.
For (j = 0; j <NUMA; j ++ ){
Historyrecord r = (historyrecord) app. Activities. Get (j );
If (! R. Finishing ){
Destroyactivitylocked (R, false );
}
R. resultasks = NULL;
}
If (App. PID> 0 & App. PID! = My_pid ){
Process. killprocess (App. PID );
}
Cleanupapplicationrecordlocked (app, false, I );
I --;
// Dump ();
}
Step 4: The above three processes are all resources for the entire process. After the preceding process is completed, resources of the activity will be recycled at a smaller granularity. Similar to the above, the list of mlruactivities stores all currently running activities, and the sorting rules are also the principle of least access. Mlruactivities. size () returns the number of activities running in the system. When the value is greater than max_activities (max_activities is a constant with a general value of 20, representing the maximum number of activities allowed to exist simultaneously in the system. Partially meet the condition
Activity to reduce memory usage. The code listing 7 shows the recycling condition:
Listing 7. Recycling condition code

// Finally, if there are too then activities now running, try
// Finish as finished as we can to get back down to the limit.
For (I = 0;
I <mlruactivities. Size ()
& Mlruactivities. Size ()> curmaxactivities;
I ++ ){
Final historyrecord R
= (Historyrecord) mlruactivities. Get (I );

// We can finish this one if we have its icicle saved and
// It is not persistent.
If (R. havestate |! R. statenotneeded )&&! R. Visible
& R. Stopped &&! R. Persistent &&! R. Finishing ){
Final int origsize = mlruactivities. Size ();
Destroyactivitylocked (R, true );
If (origsize> mlruactivities. Size ()){
I --;
}
}
}

Here, only the memory resources of the activity are recycled, and the process will not be killed or affected. When a process needs to call a killed activity, it can reply from the saved status. Of course, it may require a relatively long latency.

**************************************** **************************************** *******

Memory recovery in Linux Kernel
Lowmemorykiller
As mentioned above, the trimapplications () function executes a function called updateoomadjlocked (). If false is returned, the default function is recycled. If true is returned, the default memory is recycled. Updateoomadjlocked updates a variable named adj for each process and informs the Linux kernel that the kernel maintains an embedded data structure (that is, the progress table ), lowmemorykiller is used to check the system memory usage. When the memory is insufficient, some processes are killed and the memory is released. The android framework
The memory recovery mechanism in combination with the Linux kernel is studied.
Because all applications in the Android operating system run in an independent Dalvik virtual machine environment, the Linux kernel cannot know the running status of each process, and thus cannot maintain a proper value for each process, therefore, the Android Application Framework must provide a set of mechanisms to dynamically update the adj of each process. This is updateoomadjlocked ().
Updateoomadjlocked () is located in activitymanagerservice. Its main function is to select an appropriate adj value for the process and notify the Linux kernel to update this value. Updateoomadjlocked first calls computeoomadjlocked () to preliminarily calculate the value of adj, and then returns to updateoomadjlocked () to further modify the value. For the estimation process, see the code.
For more information, see task_struct-> signal_struct-> adj, file/kernel/include/Linux/sched. h. Essentially a variable in the process data structure, used to indicate the priority order of killing the process when out of memory occurs. Lowmemorykiller uses this variable to determine the importance of the process and releases some space when the memory is insufficient. In fact, it is in the file/kernel/Drivers/staging/Android/lowmemorykiller. C. Lowmemorykiller defines two Arrays: lowmem_adj
And lowmem_minfree. Lowmen_adj defines a series of adj key values, and each element of lowmem_minfree represents a memory threshold. In the following code, the four thresholds are 6 MB, 8 Mb, 16 MB, and 64 MB, indicating that when the memory is smaller than 64 MB, processes with a value greater than or equal to 12 will be killed and recycled. If the memory is less than 16 MB, those with a value greater than or equal to 6 will be killed and recycled. If the memory is less than 8 Mb, processes with a value greater than or equal to 1 will be killed and recycled. If the memory is less than 6 MB, all processes with a value greater than or equal to 0 will be killed and recycled. Each process in the kernel holds one
The value range is-17 to 15. The smaller the value indicates that the process is of higher importance and the lower the recycling priority. Among them,-17 indicates that automatic recycling is disabled. In Android, only 0-15 is used.
Listing 8. Each process has

Static int lowmem_adj [6] = {
0,
1,
6,
12,
};
Static int lowmem_adj_size = 4;
Static size_t lowmem_minfree [6] = {
3x512,/* 6 MB */
2x1024,/* 8 Mb */
4*1024,/* 16 MB */
16x1024,/* 64 MB */
};
Static int lowmem_minfree_size = 4;
Lowmemorykiller registers a lowmem_shrinker. lowmem_shrinker uses the cache shrinker in the standard Linux kernel. When the idle Memory Page is insufficient, the kernel thread kswapd uses the registered lowmem_shrinker to recycle the Memory Page.
Listing 9. Use the registered lowmem_shrinker to reclaim the Memory Page

Static struct shrinker lowmem_shrinker = {
. Shrink = lowmem_shrink,
. Seeks = default_seeks * 16
};

Static int _ init lowmem_init (void)
{
Task_free_register (& task_nb );
Register_shrinker (& lowmem_shrinker );
Return 0;
}
The lowmem_shrink code is in the lowmem_shrink function. The main structure of this function is given below. Lowmem_shrink traverses all processes according to the above rules, selects the processes to be terminated, and forces these processes to end by sending an unnegligible signal sigkill
Listing 10. Force Process Termination

Static int lowmem_shrink (struct shrinker * s, int nr_to_scan, gfp_t gfp_mask)
{
For_each_process (p ){
// Select processes to be forced
}
If (selected ){
Force_sig (sigkill, selected );
REM-= selected_tasksize;
} Else
Rem =-1;
Return REM;
}
Oom_killer.
If the above methods cannot release enough memory space, an out of Memory exception will occur when an application is allocated to a new process, oom_killer will do his best to kill some processes to release space. Oom_killer in Android inherits from the standard Linux 2.6 kernel and is used to process out of memory when memory is allocated. Android has not modified its implementation method. Its location is Linux/MM/oom_kill.c. Oom_killer traverses the process and calculates the badness value of all processes. Select the process with the largest badness to kill it. Function
The badness statement is as follows:
Unsigned long badness (struct task_struct * P, unsigned long uptime) function select_bad_process returns the process to be killed.
Listing 11. Return the process to be killed

Static struct task_struct * select_bad_process (unsigned long * Ppoints,
Struct mem_cgroup * MEm)
{
For_each_process (p ){
Points = badness (p, uptime. TV _sec );
If (points> * Ppoints |! Chosen ){
Chosen = P;
* Ppoints = points;
}
}
Return chosen;
}
Finally, like lowmemorykiller, the selected process is terminated by sending sigkill. Since oom_killer is no different from the standard Linux kernel, we will not study it in detail here.
Summary
This article studies the memory recovery mechanism on the Android operating system. It mainly includes the default collection at the application framework layer and lowmemorykiller and oom_killer in the Linux kernel. Generally, application developers do not need to control or modify the memory management and recovery of the system. However, it is necessary to thoroughly understand these system-level management mechanisms, especially to help design applications more rationally, enables the application process to run efficiently within its lifecycle. If system-level developers want to optimize the memory management mechanism, their understanding of the original mechanism is essential.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.