Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to manage memory in android

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to manage memory in android. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Java Heap

Java Heap, that is, the heap area in JVM. Briefly review the partition of runtime data regions in JVM:

The method stack and program counters in the orange area are private to the thread and mainly store the local data in the method.

The method area mainly stores constants and class information, and thread sharing.

The heap area is mainly responsible for storing the created objects, and the memory of almost all objects is allocated in the heap area, and it is also shared by threads.

The objects we use in android programs such as Object o = new Object () will allocate a piece of memory in the heap area for storage, and how to allocate them is solved by the virtual machine without the intervention of our developers. When an object is no longer used, there is a garbage collection mechanism (GC) in JVM, which automatically releases useless objects in the heap area and reuses memory. When we request that the memory allocated has exceeded the memory size of the heap area, an OOM exception is thrown.

In android, a heap is an area logically divided by JVM, and it is not really a physical area. The heap area does not directly map the same amount of physical memory as it does, but does not establish a mapping between logical and physical addresses until it needs to be used:

This allocates enough logical memory to the application without having to allocate a large chunk of physical memory at startup. More programs can be run in the same amount of memory.

When the heap area process GC, the excess free memory is released and will be returned to the system to reduce the use of physical memory. However, this process involves more complex system calls, and if a small amount of memory is released, the loss may outweigh the gain, so there is no need to return it to the system and continue to use it in the heap area.

In the GC process, if an object is no longer in use, but the memory it occupies can not be released, resulting in a waste of resources, this phenomenon is called memory leak. Memory leaks will lead to more and more objects in the heap area, more and more pressure on memory, and even OOM. Therefore, memory leakage is a phenomenon that we must try our best to avoid.

Process memory allocation

The memory allocation of the heap area belongs to the memory allocation within the process and is managed by the process itself. Let's talk about an application and how the system allocates memory for it.

The running memory of the system, which is often called RAM, is the running space of the application. Each application must be loaded into memory before it can be executed:

All the application processes we installed are located on the hard disk.

When an application is executed, it needs to be loaded into RAM before it can be executed (zRAM is designed to compress data to save space, which will be discussed later)

CPU interacts with RAM to read instructions, data, write data, etc.

The size of RAM is the hardware memory size of the device, so it is a very valuable resource. The common storage of modern mobile phones is 6G, 8G or 12G, and some phones specially developed for games even have 18G, but the price will keep up at the same time.

Android uses paged storage to store a process in RAM. Paging storage, to put it simply, splits memory into many small chunks, each of which occupies different chunks, which can also be called pages:

As mentioned earlier, the heap area of a process is not allocated at once, and when memory is allocated, the system allocates free pages to it; when these pages are recycled, they may be returned to the system.

The concept of page and block here is related to the paging storage of the operating system, which is not intended to be explained in detail here. Interested readers can learn about it for themselves: paging storage-Wikipedia. The "page" and "block" in this article can be loosely understood as the same concept, and there is no detailed distinction here to help understand.

Pages assigned to processes can be divided into two types: clean pages and dirty pages:

Clean page: the process did not modify it after reading data from the hard disk or requesting memory. This type of page can be recycled when it runs out of memory, because the data stored in the page can be recovered in other ways.

Dirty page: the process modifies or stores the data in the page. This kind of page cannot be recycled directly, otherwise it will cause data loss and must be stored first.

ZRAM, as a partition in RAM, can compress some types of pages and store them in zRAM when memory is low, and then call them out of zRAM when needed. The application space is saved by compression, and there is no need to schedule with the hard disk, which improves the speed.

One thing to understand here is that the operation speed in memory is much faster than that of the hard drive. Even if calling in and out of zRAM requires compression and decompression, it is much faster than interacting with the hard drive.

Out of memory management

We have always stressed that the memory capacity of mobile devices is very limited and we need to use it very carefully. Fortunately, JVM and android systems have helped us think of this a long time ago.

In the face of different memory pressures, android will have different coping strategies. From low to high is GC, the kernel swap daemon releases memory, and the low memory termination daemon kills the process to free memory; their cost is also gradually rising. Let's introduce it one by one.

GC garbage collection

GC belongs to the internal memory management mechanism of JVM, and the memory area he manages is the heap area. As we create more objects and put more pressure on the heap area, the GC mechanism will be activated and the garbage objects in the heap area will be recycled.

To tell whether an object is garbage, the virtual machine uses reachability analysis. That is, starting from some objects that are determined to be active and useful, analyze his reference chain down; if an object is referenced directly or indirectly by these objects, then it is not garbage, otherwise it is garbage. These objects that are identified as active and useful are called GC Roots:

As shown in the image above, green objects referenced directly or indirectly by GC Roots will not be recycled, while gray objects are marked as garbage if they are not referenced.

The more common types of GC Roots objects are static variables and references in the stack. Static variables are easier to understand and will not be recycled during the execution of the entire process, so they are certainly useful. Stack, which refers to the method stack in the JVM run data region, that is, the local variable reference, must be active during method execution. Because the method stack is private to the thread, the objects held by the active thread are not recycled.

Therefore, if an object is no longer used by our program, it must be dereferenced by GC Roots, otherwise it will cause a memory leak. For example, do not assign activity to a static variable, which will cause the activity to not be recycled when the interface exits.

GC does not directly recycle the whole reactor area, but divides the objects in the reactor area into two parts: the new generation and the old age.

Most newly created objects are recycled, while objects that survive multiple collections are rarely recycled later. The objects stored in the new generation are mainly objects that have just been created, while in the old era there are objects that have survived multiple GC. Then we can implement different recycling algorithms for these objects with different characteristics to improve GC performance:

For newly created objects, we need to GC them more frequently to free memory, and each time we only need to record the objects that need to be left behind, rather than marking a large number of other objects that need to be recycled to improve performance.

For objects that have survived many times of GC, you can GC others less frequently, and you only need to focus on a small number of objects that need to be recycled at a time.

The specific garbage collection algorithm will not continue to expand, you can learn here. Interested readers can read the relevant books.

The speed of a single garbage collection is so fast that we can't even feel it. However, when the memory pressure is increasing and the speed of garbage collection can not keep up with the speed of memory allocation, there will be memory allocation waiting for GC, that is, stutter. At the same time, we can't control the timing of GC, and JVM has a complete set of algorithms to decide when to do GC. If GC is triggered when we slide the interface, then the frame drop is shown. Therefore, memory optimization is very important for the performance of app.

Kernel exchange daemon

GC is an optimization for the interior of the Java program. For mobile devices, RAM is very valuable, and how to allocate memory on limited RAM resources is also a very important topic.

All our applications run in RAM. When the process keeps applying for memory allocation and the remaining memory of RAM reaches a certain threshold, it will start the kernel exchange daemon to release memory to meet the allocation of resources.

Kernel exchange daemon is a process running in the system kernel. Its main work is to free memory by recycling clean pages, compressing pages and so on. As mentioned earlier, android is an operating system based on paging storage, and each process is stored in some pages. There are two types of pagination: clean pages and dirty pages:

When the kernel swap daemon starts, it reclaims clean pages to free memory. When the process accesses the clean page again, it needs to read it again on the hard disk.

For dirty pages, the kernel swap daemon compresses them and puts them into zRAM. When the process accesses dirty pages, it needs to be unzipped from the zRAM.

Free memory by constantly recycling and compressing paging to meet new memory requests. When the memory freed in this way does not meet new memory requests, android starts the low-memory termination daemon to terminate some low-priority processes.

Low memory termination daemon

When the occupied memory of RAM reaches a certain threshold, android will terminate some processes according to the priority of the process to release memory. When the low memory termination daemon starts, it means that the memory pressure on the system is already very high, which often occurs in some poor performance devices.

The priority of the process from high to low is as follows, and the higher priority process will be terminated first:

From top to bottom, they are:

Background application: the used app will be cached in the background, and the next time you open it, you can switch more quickly. When there is insufficient memory, such applications will be killed most quickly.

The last app: for example, jumped from Wechat to a browser, where Wechat was the last app.

Home screen application: this is the launcher application, which is our desktop. If the process is kill, the screen will be temporarily blackened when it returns to the desktop.

Services: synchronization service, upload service, etc.

Perceptible applications: such as the music software that is playing, it can be perceived by us, but not at the front desk.

Foreground application: for an application currently in use, if the application has been kill, you need to report a crash exception to the user, and the experience is very poor.

Persistence (services): these are the core services of the device, such as the phone and WLAN.

System: system process. After these processes are terminated, the phone may be about to restart, just as the phone suddenly gets stuck and restarts.

Native: a very low-level process used by the system, such as our kernel exchange daemon.

When there is insufficient memory, the process will be terminated from top to bottom in accordance with the above rules to obtain memory resources. That's why our background apps have been killed in android. In order to prevent our application from being optimized, memory optimization is very important.

Thank you for reading! This is the end of this article on "how to manage memory in android". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report