The memory recycle strategy of the Android operating system _android

Source: Internet
Author: User
Tags garbage collection memory usage

Android is an operating system that is based on the Linux kernel and is oriented to mobile terminals. To adapt to its special needs as a mobile platform operating system, Google has made a special design and optimization, so that the application is closed but not quit, and the operating system for the process of recycling management. On the two levels of application Framework and Linux kernel, this paper analyzes the process resource recovery mechanism of Android operating system with the process as granularity. Readers can get a better understanding of the life cycle of the Android application from this article to build the application more rationally and efficiently.

Memory recycling in the Android operating system can be divided into two levels:

1, default memory recycle, that is, the default application Framework layer.

2, kernel-level memory recovery.

Memory recycling Lowmemorykiller, Oom_killer in the Linux kernel.

Default Memory Recycle: (code can refer to the Activitymanagerservice.java Class) Recycle Action Entry activityidleinternal ().

The trigger points for memory recycling in the Android system can be roughly divided into three different scenarios.

First, the user program invokes StartActivity (), which causes the current activity to be overwritten;

Second, the user presses the back key to exit the current application and, third, launches a new application.

These functions that trigger the recall of a memory function interface are activityidleinternal (). When Activitymanagerservice receives an asynchronous message idle_timeout_msg or Idle_now_msg, activityidleinternal () is invoked. Idle_now_msg by the activity of the switch and Activiy focus of the changes, such as events, idle_timeout_msg in the event startup timeout, the general timeout is set to 10s, if 10s within a Activit Y still does not start successfully, the asynchronous message idle_timeout_msg is sent for resource reclamation. The main task of activityidleinternal () is to change the status information of the activity in the system and add it to the list of different states. Its main work is as follows:

First, the scheduleappgcslocked () method is invoked to notify all ongoing tasks for garbage collection. Scheduleappgcslocked () will dispatch the garbage collect of the JVM to reclaim part of the memory space, just to notify each process to process its own garbage check and schedule the collection time instead of synchronizing the collection.

Then, remove all the contents of the Mstoppingactivities and Mfinishigactivities lists, temporarily in temporary variables. The two lists store the active objects that are currently in the state of stop and Finishi. For a stop list, if the activity's finish state is true, 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 call the R Esumetopactivity () runs the next activity. If the finish status is false, the call to Stopactivitylocked () notifies the customer that the process is stopping the activity, which typically occurs after the call to StartActivity (). For the finish list, call destroyactivitylocked () directly to notify the customer that the process destroys the target activity. The destroyactivitylocked function here does not really change the memory usage, just change its state to "allow recycling", and the real recycle is in the trimapplications () function that is about to be invoked below.

Private final void Trimapplications () {
synchronized (this) {
//I-Remove unused application processes who SE 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 many activities now run Ning, try to
//finish as many as "we can" to "get" and "back" to the limit.
(3) Do something
}
}

(1) After the program executes to Trimapplications (), first check the process in the Mremovedprocesses list. The Mremovedprocesses list consists primarily of crash processes, processes that are not responding within 5 seconds, and which are selected by the user for forced shutdown, as well as application development which 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 supports the SETOOMADJ () interface, updateoomadjlocked will modify the Adj value and notify the Linux kernel, the kernel according to Adj value and memory to make Dynamically Manage process resources (Lowmemorykiller and Oom_killer) with situations. If updateoomadjlocked () returns false, the current system does not support the Setoomadj () interface, and the default resource collection is local.

(3) Finally, if excessive activity is still running, recycle the excess activity. Most of the code for Trimapplications () deals with default resource recycling in the case where Oom_killer does not exist, and the following is a further analysis of its default recycle process, where the code is written (2). The recycling process can be broadly described as follows.

Step one, get the collation of all currently running process mlruprocesses,mlruprocesses by the most recent use time. Processes that cannot be shut down in Mlruprocesses include processes running service, running broadcast receiver processes, and so on.

Step two, set the current maximum number of running processes Curmaxprocs = Curmaxprocs + Numserviceprocs (that is, the sum of 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, traverses all currently running processes, kills those processes that match the criteria, and frees up memory. The condition that the process is killed is that it must be a persistent process, that is, a non-system process, must be an empty process, that is, no activity exists in the process. If you kill a process that has an activity, it is possible to turn off the program that the user is using, or to make the application recovery time delay larger, thus affecting the user experience; there must be no broadcast receiver. Running broadcast receiver generally waits for an event to occur, and the user does not want such programs to be forced off by the system; The number of service in the process must be 0. The process of having a service is most likely to provide a service for one or more programs, such as GPS positioning services. Killing such a process will render the other processes not serving properly.

Step three, check the currently running process again, and if Mremovedprocesses.size () is still greater than curmaxprocs, relax the condition and recycle again.

Step four, the above 3 processes are all resource recycling for the entire process. After the above procedure has been completed, the resources of the activity will be recycled on a smaller granularity. Similar to the above, the list Mlruactivities stores all current running activity, and the collation is also the least-accessible rule. 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, with a general value of 20, representing the maximum allowable simultaneous presence in the system). Activity). The activity that partially satisfies the condition is recycled to reduce memory usage. The only activity memory that is recycled here does not kill the process, nor does it affect the running of the process. When a process needs to invoke a killed activity, it can be restored from the saved state, although it may require a relatively long delay.

Memory recycling in the Linux kernel

Lowmemorykiller

A function called updateoomadjlocked () is executed in the trimapplications () function, and if False, the default recycle is performed and the default memory recycle is not performed if true.
updateoomadjlocked will update a variable named adj for each process and inform the Linux kernel that the kernel maintains a data structure containing adj (that is, the process table) and checks the usage of system memory through Lowmemorykiller. Kills some processes and frees memory in the event of low memory.

Since all applications in the Android operating system are running in a stand-alone Dalvik virtual machine environment, the Linux kernel is not aware of the state of each process and cannot maintain a suitable adj value for each process, so the Android application The Framework must provide a mechanism to dynamically update the adj of each process. This is updateoomadjlocked ().

Android Sets the default five recovery priorities based on the components that are running in the process and their status:

Importance_foreground:
Importance_visible:
Importance_service:
Importance_background:
Importance_empty:

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.