Http://www.ibm.com/developerworks/cn/opensource/os-cn-android-mmry-rcycl/index.html
Operating Environment of Android APP
Android is a Linux-based kernel for mobile terminal operating systems. In order to adapt to its special needs as a mobile platform operating system, Google has made a special design and optimization,
Make the process scheduling and resource management and other platforms of Linux have obvious differences. It consists of the following levels:
Application Framework
The application Framework separates the entire operating system into two parts. For app developers, all apps are running on the application Framework,
There is no need to care about the bottom of the system. The application Framework layer provides a rich application programming interface for application developers, such as Activity manager,content Provider,
Notification Manager, as well as various widgets resources. At the application Framework level, Activity is the most basic component of an APP. In general, each Activity
Corresponds to a view on the screen (or one screen), an APP can have one or more Activity. The application is packaged into an. apk format file that is interpreted by the Dalvik VM for execution.
Dalvik VMS
The Dalvik virtual machine uses a register schema rather than the JVM's stack structure. The. class file compiled by the Java program does not interpret execution in Dalvik. So Google offers a DX tool that
Used to convert a. class file into a. dex format that DALIVK can recognize. Details of specific Dalvik VMs are not the focus of this article and are no longer discussed below.
Linux kernel
As mentioned above, all apps are written in Java code and interpreted in the Dalvik VM. In the Android operating system, each Instance for each Dalvik VM corresponds to the
A process in the Linux kernel. You can use the ADB shell tool to view the current process in the system. As shown, Android2.3.3 the list of processes in the kernel after startup.
Figure 1. List of processes in Android 2.3 (partial)
Figure 1. List of processes in Android 2.3 (partial)
In Figure 1, each entry with a UID ID of app_xx is a process occupied by an app, and the Android design allows each application to be interpreted by a separate Dalvik instance,
Each Linux kernel process loads a Dalvik instance, providing the app's operating environment in this way. This way, each APP's resources are completely shielded from each other. while also introducing the
The difficulty of inter-process communication, but also brings about stronger security.
Android Memory Recycling Principle
The following will analyze the Android operating system resource management mechanism from the application Framework and Linux kernel two levels.
The reason why Android uses a special resource management mechanism is that it is designed to target mobile terminals, and all available memory is limited to system RAM, and the corresponding optimization scheme must be designed for this limitation.
When the Android application exits, it does not clean up the memory it consumes, and the Linux kernel process continues to exist, so-called "quit without shutting down". This allows the user to get a response at the first time when invoking the program.
When system memory is low, the system activates the memory reclamation process. In order not to affect the user experience (such as killing the current active process) due to memory reclamation,
Android based on the components running in the process and their status specifies the default five recycle priority:
Importance_foreground:
Importance_visible:
Importance_service:
Importance_background:
Importance_empty:
The order of recovery for these priority levels is Empty process, Background process, Service process, Visible process, Foreground process. See the http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html file for the partitioning principle.
Activitymanagerservice centrally manages memory resource allocations for all processes. The Activitymanagerservice object must be called before all processes need to request or free memory.
After obtaining its "license", the next step can be made, or activitymanagerservice will "do it" directly. A few of the activitymanagerservice in the class are related to memory recycling
Important member methods are as follows: Trimapplications (), updateoomadjlocked (), activityidleinternal (). These member methods are primarily responsible for the Android default memory recovery mechanism,
If the memory recycling mechanism in the Linux kernel is not disabled, the default recycle is skipped.
Default Recycle process
Memory recycling in the Android operating system can be divided into two levels, that is, the default memory recovery and kernel-level memory recovery, this chapter focuses on the default memory recycling mechanism, the Linux kernel-level memory recovery mechanism
will be introduced in the next section. All code in this chapter can be found in Activitymanagerservice.java.
Recycle Action entry: activityidleinternal ()
The trigger point for memory recovery in Android is broadly divided into three scenarios. First, the user program calls StartActivity (), which causes the activity of the current event to be overwritten;
Second, the user presses the back key, exits the current application, and third launches a new application. The function interfaces that are ultimately called by these events that trigger memory reclamation are activityidleinternal ().
When Activitymanagerservice receives an asynchronous message idle_timeout_msg or Idle_now_msg, activityidleinternal () is called. The code is as follows:
Listing 1. How to handle idle_now_msg
Case idle_now_msg:{
IBinder token = (ibinder) msg.obj;
Activityidle (token, NULL);
}
Break
Listing 2. How to handle idle_timeout_msg
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
The idle_now_msg is triggered by events such as the switching of the activity and changes in the Activiy focus, idle_timeout_msg in the event that the activity starts to timeout.
Typically this timeout is set to 10s, and if an Activity within 10s does not start successfully, an asynchronous message idle_timeout_msg will be sent for resource recycling.
The main task of activityidleinternal () is to change the status information of the Activity in the system and add it to a different state list. Its main work is as follows:
First, call the Scheduleappgcslocked () method to notify all the in-progress tasks to be garbage collected. Scheduleappgcslocked () will dispatch the JVM's garbage collect,
Reclaim a portion of the memory space, which is simply to notify each process of its own process garbage check and schedule the collection time, rather than synchronous reclamation. Then, remove mstoppingactivities and mfinishigactivities
All content in the list, temporarily in a temporary variable. These two lists store the activity object with the current status of stop and Finishi, respectively. For the stop list, if the activity's finish
The status is true to determine if you want to stop immediately, call Destroyactivitylocked () to notify the target process to call the OnDestroy () method if you want to stop immediately, otherwise, first call the
Resumetopactivity () runs the next Activity. If the finish status is False, call stopactivitylocked () to notify the client process to stop the activity, which typically occurs in
After calling StartActivity (). For the finish list, call destroyactivitylocked () directly to notify the client process to destroy the target Activity.
The destroyactivitylocked function here does not really change the use of memory, just change its state to "allow recycling", and really recycle it in the trimapplications () function that is about to be called below.
Recycle 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 is too many activities now running, try to
Finish as many as we can get to the limit.
(3) Do something
}
}
The positions of the three ordinal numbers in Listing 3 are respectively responsible for the following tasks:
(1) When the program executes to Trimapplications (), first check the process in the Mremovedprocesses list. The Mremovedprocesses list mainly contains the crash process,
There is no response within 5 seconds and is selected by the user in the forced shutdown process, and the application development this calls Killbackgroundprocess to kill the process. Call process.killprocess to kill all such processes.
(2) Call the updateoomadjlocked () function, if successful return, the Linux kernel Support Setoomadj () interface, updateoomadjlocked will modify the value of Adj and notify the Linux kernel,
The kernel dynamically manages process resources (Lowmemorykiller and Oom_killer) based on adj values and memory usage. If updateoomadjlocked () returns false, it indicates that the current system does not support
Setoomadj () interface, the default resource collection will be done locally.
(3) Finally, if too much activity is currently running, the excess activity is recycled. Most of the code for Trimapplications () is in the process of handling the default resource collection that Oom_killer does not exist.
The following is a further analysis of its default recycling process, where the code listing is marked (2). The recycling process can be described as follows.
Step one, gets the collation of all currently running processes in mlruprocesses,mlruprocesses by the most recent usage time. To count processes that cannot be closed in mlruprocesses,
These processes that cannot be closed include the process that runs the service, the process that runs the broadcast receiver, and so on, as shown in the following code.
Listing 4. Counting processes that cannot be closed
if (app.persistent | | app.services.size ()! = 0
|| App.curreceiver! = NULL
|| App.persistentactivities > 0) {
Don ' t count processes holding services against our
Maximum process count.
numserviceprocs++;
}
Step two, set the current maximum number of running processes Curmaxprocs = Curmaxprocs + Numserviceprocs (that is, the default maximum number of processes and the number of processes running the Service),
If the number of current processes mremovedprocesses.size () is greater than this value, traverse all currently running processes, kill those processes that meet the criteria, and free up memory. The cleanup process is shown in Listing 5 (part of the code omitted).
As you can see from the code in Listing 5, the condition that the process is killed is:
It must be a non-persistent process, not a system process;
Must be an empty process, that is, no activity exists in the process. If the Activity process is killed, it is possible to close the program that the user is using, or to make the application recover more time-delayed, thereby affecting the user experience;
There must be no broadcast receiver. Running broadcast receiver is generally waiting for an event to occur, and the user does not want such programs to be forcibly shut down by the system;
The number of service in the process must be 0. The existence of a service process is likely to provide some kind of services, such as GPS location services, for one or more programs. Killing such a process will cause other processes to not service properly.
The above conditions are indispensable.
Listing 5. Cleanup process
if (!app.persistent && app.activities.size () = = 0
&& App.curreceiver = = 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 are not buggy
or evil, and would 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 three, check the currently running process again, and if Mremovedprocesses.size () is still greater than curmaxprocs, then the relaxation condition is recycled again. The judging conditions are shown in Listing 6 (part of the code omitted).
In the following code, when the value of the Boolean variable canquit is true, the process can be recycled. The value of Canquit is divided into two steps, first of all based on the properties of the process.
1. A non-persistent process, that is, not a system process, must be
2. There must be no broadcast receiver;
3. The number of service in the process must be 0;
4. The number of activity for the persistent type is 0.
Unlike step two, the only difference is in 4th, where the process is not required to be an empty process, as long as there are no persistent types of Activity in the process
(Activity is whether the persistent type is specified in development phase). When these conditions are met, the properties of each activity in the process are then checked, and when all the activity in the process
must also meet three conditions: The activity's state has been saved, is currently in an invisible state, and the activity has been Stop. At this point the kill process will only slow down the next time the program is loaded,
The next boot will revert to the state before shutdown and will not have a fatal impact on the user experience, so the Canquit is set to true. This situation is different from the method of recovery of step two,
Because the number of activity in the process is not 0, the next step is to perform a destroyactivitylocked () destroy on each activity, and then kill the process.
Listing 6. Perform destroyactivitylocked () destruction
Boolean canquit =!app.persistent && App.curreceiver = = NULL
&& app.services.size () = = 0
&& 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.resultto = null;
}
if (app.pid > 0 && app.pid! = my_pid) {
Process.killprocess (APP.PID);
}
Cleanupapplicationrecordlocked (app, False, I);
i--;
Dump ();
}
Step four, the above 3 processes are resource recycling for the entire process. After the above process has been completed, the resource of the Activity will be recycled at a much smaller granularity.
Similar to the above, the list Mlruactivities stores all currently running Activity, with the same collation as the least access principle. Mlruactivities.size () returns
The number of Activity that is running in the system, when it is greater than max_activities (Max_activities is a constant, the general value is 20, which represents the maximum allowed in the system simultaneously
Activity that exists). The Activity that partially satisfies the condition is recycled to reduce memory usage. The recycle condition code is shown in Listing 7:
Listing 7. Recycle condition Code
Finally, if there is too many activities now running, try to
Finish as many as we can get 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 has 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--;
}
}
}
Only the memory resources of the Activity are recycled, and the process is not killed and the process is not affected. When the process needs to invoke the Activity that was killed,
You can reply from a saved state, which may require a relatively long delay.
Memory recycling in the Linux kernel
Lowmemorykiller
As mentioned above, a function called updateoomadjlocked () is executed in the trimapplications () function, and if False is returned, the default collection is performed.
Returns true to not perform the default memory reclamation. updateoomadjlocked will update a variable named adj for each process and tell it to the Linux kernel,
The kernel maintains a data structure that contains adj (that is, the process table) and checks the usage of the system memory through Lowmemorykiller, killing some processes and freeing memory in the case of low memory.
The following is a study of the memory-recycling mechanism that matches this Android Framework with the Linux kernel.
Since all applications in the Android operating system are running in a standalone Dalvik virtual machine environment, the Linux kernel cannot know the running state of each process and cannot
Maintaining an appropriate Adj value, 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, whose primary role is to select a suitable adj value for the process and notify the Linux kernel to update the value.
Updateoomadjlocked first calls computeoomadjlocked () to calculate the value of the Adj, and then returns to Updateoomadjlocked () to further revise its value. The estimation process can be found in the code.
About adj, which is defined in Task_struct->signal_struct->adj, file/kernel/include/linux/sched.h. The substance is a variable in the process data structure that represents the occurrence
The priority order of the kill process when out of Memory. Lowmemorykiller uses this variable to judge the importance of the process and to free up some space when the memory is low, in fact the file is now/kernel/drivers/staging/android/lowmemorykiller.c. Lowmemorykiller defines two arrays: Lowmem_adj and Lowmem_minfree. where Lowmen_adj
A series of Adj key values are defined, and each element of Lowmem_minfree represents a memory threshold value. The four thresholds in the following code are 6MB,8MB,16MB and 64MB, respectively,
The processes that adj greater than or equal to 12 will be killed and recycled when memory is less than 64MB, respectively.
When memory is less than 16MB, those processes adj greater than or equal to 6 will be killed and recycled, and those processes with adj greater than or equal to 1 will be killed and recycled when the memory is less than 8MB.
When memory is less than 6MB, all processes with adj greater than or equal to 0 will be killed and recycled. Each process in the kernel holds a Adj value range of 17 to 15,
The smaller the value, the higher the importance of the process, and the lower the recycling priority, where 17 represents disabling automatic recycling. Only 0-15 of the Android system is used.
Listing 8. Each process holds a adj
static int Lowmem_adj[6] = {
0,
1,
6,
12,
};
static int lowmem_adj_size = 4;
Static size_t Lowmem_minfree[6] = {
3 *,/* 6MB */
2 * 1024x768,/* 8MB */
4 * 1024x768,/* 16MB */
* 1024x768,/* 64MB */
};
static int lowmem_minfree_size = 4;
Lowmemorykiller Register a Lowmem_shrinker,lowmem_shrinker is implemented using the Cache Shrinker in the standard Linux kernel,
When the free memory page is low, kernel thread KSWAPD will reclaim the memory page with the registered Lowmem_shrinker.
Listing 9. Reclaim memory pages with registered Lowmem_shrinker
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 function Lowmem_shrink, and the main structure of the function is given below. Lowmem_shrink Traverse all processes according to the above rules,
Select the process that needs to be closed by sending a signal that cannot be ignored SIGKILL force the end of these processes
Listing 10. Force End Process
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 none of the above methods can free up enough memory space, an out of memory exception will occur when the application is allocated for the new process.
Oom_killer will make a final effort to kill some of the process to free up space. Oom_killer in Android inherits from the standard Linux 2.6 kernel for allocating memory
Out of Memory processing. Android does not modify the way it is implemented. Its position is in the linux/mm/oom_kill.c. Oom_killer traversal process,
and calculate the badness value of all processes, select the badness the largest process to kill it. The declaration of the function badness is as follows:
unsigned long badness (struct task_struct *p, unsigned long uptime) function select_bad_process returns the process that will be killed.
Listing 11. Return to the process that will be killed
The 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, as with Lowmemorykiller, the selected process is ended by sending SIGKILL. Since Oom_killer is no different from the standard Linux kernel, it is no longer studied in detail.
Summarize
This paper studies the mechanism of memory recovery on the Android operating system. This includes the default recycling of the application Framework layer and the Lowmemorykiller in the Linux kernel,
Oom_killer. In general, application developers do not need to control or modify the system's memory management and recycling, but in-depth understanding of these system-level management mechanisms is still necessary,
In particular, it helps to design applications more rationally, enabling the application's processes to run efficiently throughout its lifecycle. System-level developers, if they want to optimize the memory management mechanism,
The understanding of the original mechanism is an essential prerequisite.
Memory recovery mechanism for Android OS (reprint)