Hello, I’m Clock. I checked Jane’s book and found that I hadn’t updated my blog for more than a month. I was planning to go to the cinema with a girl to see Your Name and then have sex with her.
As a result, she had to go back to her company because the girl had something to do… Then I have to stay at home, since the girl is not at home, I happen to have been doing memory leak optimization work for the project, so I will write a personal summary.
What is a memory leak
For different language platforms, the algorithm of tag collection is different. For example, Android (Java) adopts GC-root tag collection algorithm. Here’s an example of Android’s memory reclamation strategy (from Google 2011’S IO Conference)
Each round node in the figure represents the memory resource of the object, and the arrow represents the reachable path. If there is a reachable path between the round node and GC Roots, it indicates that the current resource is being referenced and the VIRTUAL machine cannot reclaim it (yellow node in the figure). Conversely, if there is no reachable path between the round node and GC Roots, it means that the object’s memory resources are no longer referenced by the program and can be reclaimed by the system virtual machine during GC.
With that in mind, it’s time to talk about what a memory leak is. By definition, a memory leak on the Android (Java) platform is when an unused object resource remains on a reachable path with GC-root so that the system cannot reclaim it. For the simplest example, we register a broadcast receiver in the onCreate function of the Activity, but we do not unregister the receiver in the onDestory function. When the Activity is finished, the Activity object has run its life cycle. It should be reclaimed, but because there is no de-registration, there is still a reachable path between the Activity and gC-root, so the Activity is destroyed, but the memory resources occupied by the Activity cannot be reclaimed. There are many similar chestnuts in fact, not an example. For more information on Android (Java) memory reclamation management, check out the following resources:
- Understanding the Java Virtual Machine in Depth: Advanced JVM Features and Best Practices (version 2)
- Google IO 2011 Memory management for Android Apps
Source of the leak
With the theory of memory leaks behind you, let’s categorize the source of memory leaks. Here I put them in the following three categories:
- Autocoding induced
Caused by the project developer’s own code.
- Caused by third party code
There are two types of third-party code here: third-party non-open source SDKS and open source third-party frameworks.
- System reason
Leaks caused by the Android system itself, such as problems with WebViews, InputMethodManager, etc., and problems with some third-party ROMs.
Location of leak
Unlike the flash back BUG, memory leak is relatively difficult to check. The extreme case is that when you find the memory leak problem in OOM, it will cause too much impact on users to check and deal with the problem. For this reason, we can find problems as early as possible in the code and do not wait until online to fill the hole. Here are some tools I often use to troubleshoot memory leaks.
- Static code analysis tool — Lint
Lint is a tool that comes with Android Studio. Use a simple pose like Analyze -> Inspect Code and select the area you want to scan
Lint alerts you to codes that might cause leaks.
Lint here is just a primer on how to play Lint, but there are actually a lot more ways to play Lint, so you can learn more on your own. In addition to Lint, static code analysis tools like FindBugs and Checkstyle are also great.
- StrictMode – StrictMode
StrictMode is an API provided by the Android operating system, which can be introduced in the development environment to expose problems earlier. The official documentation link is below (science online required) :
Developer.android.com/reference/a…
StrictMode is only enabled in test environments and will be turned off in production, usually with buildconfig.debug.
After StrictMode is enabled, add the StrictMode filter Tag to the place where the logs are filtered. If the mobile phone is connected to the computer for development, observe StrictMode under the Tag regularly. Generally, you will see a lot of red alarm logs. We need to check if it’s related to a memory leak.
- LeakCanary
Square is a memory analysis tool with an official address:
Github.com/square/leak…
LeakCanary, like StrictMode, needs to be integrated into the project code, but the code is very simple, as shown in the official example below.
Build. Gradle adds two or three lines of code to your Application. The above is just a brief introduction, there are more tips for using posture to read it in detail under the Wiki FAQ:
Github.com/square/leak…
I have two feelings about using LeakCanary:
- When a leak occurs, LeakCanary pops up and generates a record of the corresponding heap storage information, which gives us a more intuitive sense of the hidden memory leak problem, but from practical use, LeakCanary does not actually leak every time. In order to determine whether there is a problem, we need to make final determination with the help of MAT.
- Android has a number of issues that cause application memory leaks, and the AndroidExcludedRefs class for LeakCanary helps us deal with a number of these issues.
- Android Memory Monitor
AndroidStudio provides a tool for monitoring the application’s memory usage status. It is also a very useful tool in development. It can be used to print out the memory status information.
The memory information obtained by printing is as follows. Leaking activities and some repeated strings can be analyzed through the green triangle button in the upper right corner. Currently, only these two are supported, and we hope Google can add more optional analysis rules later
Similarly, here is just a simple introduction, about its use in the official documentation has been said in great detail, the need for children’s shoes to view the link below (need to science online) :
Developer.android.com/studio/prof…
- Memory Analyzer (MAT)
The old brand analysis tool can be downloaded from www.eclipse.org/mat/. There are many articles on the use of MAT on the Internet, you can find them by yourself. The above file of stored information generated by Android Memory Monitor can be configured with MAT to analyze and use. Since the Hprof file generated by Android Memory Monitor is not in standard format, it needs to be converted and imported into MAT
Then use OQL to locate the leaking object first
Finally, the GC Root location is parsed by excluding all reference chains other than strong references
MAT is relatively cumbersome to use, but it can be a powerful tool to locate root problems.
- The adb shell command
Adb shell dumpsys meminfo [PackageName] prints application memory information for the specified PackageName
Using this command, you can intuitively observe the Activity leakage problem, which is a common way for me to analyze. In addition to using commands, AndroidStudio also provides the following functions, which have the same effect as using commands.
If you are interested in adb shell commands, see the resources provided below for more information:
- adbshell.com/
- Github.com/mzlogin/awe…
The above are the tools I use for memory leak analysis, and they are usually combined. After all, each tool has its advantages and disadvantages. Using multiple complementary tools to analyze problems can greatly improve our efficiency and final results.
A leak resolution strategy
After talking about tools, let’s finally talk about strategies for solving memory leaks. I summarize it as the following three points:
- After completing the development of required functions, optimize the memory leak problem;
- When there are multiple leakage sources, the leakage caused by core functions is preferentially processed, and the leakage caused by frequently used functions is preferentially processed.
- Handle leakage to avoid affecting the original code logic. After optimization, it is best to let the tester go through related functions to avoid introducing unknown bugs.
conclusion
There are many scenarios and solutions on the web for coding memory leaks, and you can use the search engine yourself. By mastering the analysis methods and the accumulation of leak scenarios and solutions, we believe that you will be able to deal with memory leak problems easily. Of course, not all memory leaks can be dealt with, such as when the source of the leak mentioned in Section 2 is third party code. Recently, in the process of investigation, many third-party SDKS were found to have leakage problems. In this case, we have to find alternative SDKS to replace them. The above is my summary of memory leak analysis, if there are any mistakes and deficiencies, please point out.
For more articles, please check out my simple book:
www.jianshu.com/users/ec95b…