Basic knowledge of Android memory notes

Basic knowledge of Android memory notes


Memory is an important indicator of performance and can directly affect user experience, especially OOM will directly lead to process crash.

And memory is a huge knowledge system, and there is no way to explain it clearly in one or two sentences. Therefore, a series of articles will be used to consolidate memory knowledge.

1. What is memory?

From the knowledge of computer principles, we know that memory is a kind of hardware with fast read and write speed, and data will be lost when it is turned off. The CPU reads and writes data through the memory.

2. Brief description of Java memory

Apps on Android all run on the Android virtual machine (Dalvik virtual machine is used below 5.0, and ART virtual machine is used above 5.0), and the Android virtual machine is essentially a Java virtual machine, so Android memory and Java memory are closely related. related. To explore Android memory, you must first understand the Java memory model.

1. JVM memory model

This question can be described as a high-frequency interview question, and there are countless articles on the Internet to explain it. The most classic is the picture below.

insert image description here

  1. Method area: class information, static variables, constants, etc. are saved here, which are shared by threads.
  2. Virtual machine stack: saves the local variable table, operation stack, dynamic link, method exit, and object pointer. The variables here are references . Thread private.
  3. Native method stack: This part is for Native methods, that is, c or c++ functions. Thread private.
  4. Heap: **Each object is allocated on the heap. References are allocated in the virtual machine stack, and these references will point to real objects in the heap. **Thread sharing
  5. Program counter: record the current thread execution to which line. Thread private.

Explain with a simple piece of code:

// 类名、常量池等信息存储在方法区
public class Company {
    
    

    // 存储在方法区
    public static int DEFAULT_AGE = 10;

    // 成员变量在堆里
    private Map<String, Float> mSalary = new HashMap();

    private void createSalary() {
    
    
        // 临时变量在虚拟机栈里
        Map<String, Float> salary = new HashMap<>();
    }
}

2. Garbage collection GC of JVM

Thanks to the garbage collection strategy of the JVM, Java code does not need to manage memory allocation and recovery like C/C++ code.

In C/C++, you need to apply for memory through methods such as malloc, and release it through methods such as free after use. In Java, when we new out an object, most of the time we don't care about when to release it. This is the work of the JVM to help us reclaim memory, which is called garbage collection GC (Garbage Collection).

2.1. How to judge which classes should be recycled?

To determine whether a class should be recycled, the JVM adopts the reachability strategy.

The virtual machine defines a series of GC Roots . If an object is reachable from the GC Root , it will not be recycled. If this object is not reachable from any GC Root, the virtual machine will consider it an object that is no longer used and recycle it.

The following is the GC Root

  • Objects referenced in the virtual machine stack (local variable table in the stack frame)
  • The object referenced by JNI (generally speaking, Native method) in the local method stack
  • Objects referenced by class static properties in the method area
  • Objects referenced by constants in the method area

insert image description here

As shown in the figure above, both a and b are recyclable objects.

2.2, GC algorithm

  1. mark-and-sweep
    • Algorithm: Mark all objects that need to be recycled (unreachable by GC Root), and then recycle these objects at once.
    • Pros: Simple
    • Disadvantages: It is easy to cause a lot of discontinuous memory fragments, resulting in insufficient utilization of memory. less efficient.
  2. copy algorithm
    • Algorithm: Divide the memory into two pieces, and only use one of them at a time. Copy the surviving object to another block during GC, and then clean up the used part
    • Pros: Simple to run.
    • Disadvantages: Waste of resources, the available memory is half of the maximum memory.
  3. Mark-Collating Algorithm
    • Algorithm: Mark all objects that need to be recycled (unreachable by GC Root), then move the surviving objects to one end of the memory, and finally clean up the objects that need to be recycled.
    • Advantages: Avoid continuous fragmented memory and make full use of memory
    • Disadvantages: relatively high overhead
  4. Generational Collection Algorithm
    • Algorithm: Divide objects into new generation and old generation, each generation has its own recovery strategy. The new generation uses the copy algorithm, and the old generation uses the mark-sort algorithm.
    • Advantages: Combines the advantages of various algorithms.

At present, the virtual machine adopts the generational recycling algorithm. Because the young generation has fewer surviving objects, a large number of objects will be recycled each time the GC uses the copy algorithm, only the cost of copying a small number of inventory objects is required. However, there are many surviving objects in the old generation, so the mark-sort algorithm is used.

3. Android memory

As mentioned in the second section, Android apps run on the Android virtual machine, but it does not mean that the memory of Android is only the memory of the virtual machine. In fact, the memory composition of Android is more complicated than imagined.

Android is an operating system, which itself is developed based on Linux, so memory management is also based on Linux. Due to space reasons, this article does not explain the memory management of linux.

dumpsys meminfo

This command is used to view memory usage. Using this command directly will output memory information sorted by RSS and PSS, classified as follows:

type explain
process Sort by process
OOM adj Display the process status of each category according to Native, System, Persistent, etc.
category Display the process status of each category according to Dalvik, Native, .art mmap, etc.

However, it is rare to use this command directly. Usually, the process number is added to check the memory occupied by the process.

adb shell dumpsys meminfo <pid>

insert image description here

The memory information obtained through this command is an integral part of the Android memory.

1. What is Pss Rss Vss

From the picture we can see Pss Total and Rss Total, first explain what it means.

  • Pss Proportional Set Size The actual physical memory size used
  • The actual physical memory size used by Rss Resident Set Size
  • Vss Virtual Set Size The size of virtual memory used

Both Pss and Rss refer to the occupied physical memory, but the calculation method is a little different.

  • Rss is calculated by taking into account the total size of shared libraries used .
  • When calculating, Pss will allocate the size of the shared library in proportion to the processes used.

Assuming that the A process uses 500KB of physical memory, he and the B process both use a 100KB shared library, then the RSS of the A process = 500 + 100 = 600KB, and the Pss = 500 + 100/2 = 550KB.

Usually Pss has more reference value.

Vss is the size occupied by virtual memory. Because c/c++ applies for virtual memory through the malloc() function , if this memory is not accessed, there will be no actual physical memory occupation. Only when a page fault occurs during access will real physical memory be allocated.

2. The meaning of each part

first part

insert image description here

Let's first look at the meaning of the horizontal axis.

name meaning
Pss Totoal Total Pss occupied
Private Dirty Process-private, in-memory data that has changed compared to disk
Private Clean Process-private, in-memory data that has not changed compared to disk
SwapPss Dirty Linux has a feature of the ZRAM feature, which is displayed when it is turned on
Rss Total Total Rss Occupied

Look at the vertical axis

name meaning
Native Heap Memory allocated by C/C++ code
Dalvik Heap Memory allocated by the Android virtual machine
Dalvik Other Class data structure, memory allocated by index
Stack Occupy memory
Cursor Space occupied by CursorWindow, related to SQL
Ashmem Anonymous shared memory, this type of memory is associated with the cache shrinker, which can control the cache shrinker to reclaim these shared memory at an appropriate time
Gfx dev Memory occupied by /dev/kgsl-3d0
Other de v Memory occupied by internal driver
.so mmap The memory occupied by the mapped .so code
.jar mmap Memory occupied by Java file code
.apk mmap The memory occupied by the apk code
.ttf mothers The memory occupied by the ttf file code
.dex mmap Memory occupied by the mapped .dex code
.oat mmap The memory occupied by the code shadow image.
.art mmap Code occupied by the heap image
Other mmap Memory used by other files

the second part

insert image description here

name composition
Java Heap Dalvik Heap的Private Dirty
.art mmap的Private Dirty + private Clean
Native Heap Native Heap的Private Dirty
Code .so mmap
.jar mmap
.apk mmap
.ttf mmap
.dex mmap
.oat mmap的Private Dirty + Private Clean
Stack Stack的private Dirty
Graphics Gfx dex
EGL mtrack
GL mtrack的P rivate Dirty + Private Clean
Private Other Native Heap
Dalvik Heap
Heap_UNKNOWN的Private Dirty + Private Clean
System Native Heap
Dalvik Heap
HEAP_UNKNOWN的Pss + SwapPss Dirty - Private Dirty - Private Clean
TOTAL PSS Native Heap
Dalvik Heap
HEAP_UNKNOWN的Pss + SwapPss Dirty
TOTAL SWAP PSS Native Heap
Dalvik Heap
HEAP_UNKNOWN的SwapPss Dirty

Reference article:

https://www.jianshu.com/p/9edfe9d5eb34

https://juejin.cn/post/6844904096541966350

https://developer.android.google.cn/studio/command-line/dumpsys?hl=zh-cn

Guess you like

Origin blog.csdn.net/qq_43478882/article/details/129227950