Memory reclaim policy in Android operating system, android reclaim

Source: Internet
Author: User

Memory reclaim policy in Android operating system, android reclaim

Memory collection in the Android operating system can be divided into two levels: 1. Default memory collection, that is, the default collection at the Application Framework layer. 2. kernel-level memory recovery. In Linux, lowmemorykiller and OOM_killer are recycled from memory.

Default memory recycle: (check the code for the ActivityManagerService. java class) the recycle 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.
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 the stop list, if the finish status of the activity is true, determine whether to stop immediately. If you want to stop 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 the finish list, call destroyActivityLocked () to notify the client 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.

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 many activities now running, try to         // finish as many as we can to get back down to the limit.            (3)do something     }  }

(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 codes of trimApplications () process default resource reclaim when Oom_killer does not exist, and further analyze the default recycle process (that is, the location marked (2) in the Code. 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 processes that cannot be shut down in mLruProcesses. These processes that cannot be shut down include the processes that run the service and the processes that run the broadcast proceser.
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. If a process is killed, it must be a non-persistent process, that is, a non-system process. It must be a null process, that is, no activity exists in the process. If the active process is killed, it is possible to close the program that the user is using, or increase the latency of application recovery, thus affecting the user experience. No broadcast receiver er is required. Generally, running broadcast explorer is waiting for an event. You do not want this type of program to be forcibly disabled by the system. The number of services in the 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.
Step 3: Check the currently running process again. If mRemovedProcesses. size () is still greater than curMaxProcs, the condition is relaxed and recycled again.
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. Partial Activity that meets the condition will be recycled to reduce memory usage.
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
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.
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 ().

For details, refer to: here to write the link content

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.