Android internal slave Leakage

Source: Internet
Author: User

Conversion from: http://www.cnblogs.com/lbeing/archive/2010/09/29/1838858.htmlandroidmemory Leakage

The memory of a recently written program is constantly increasing. You can search for relevant information online. As follows:

0: cause: Java memory management and Memory leakage (http://immortal.5d6d.com/thread-36-1-1.html)
Java Memory leakage is a problem that every Java programmer will encounter. The program runs normally locally, but when deployed to the remote end, there will be an unlimited increase in memory, and finally the system is paralyzed, so how can we test the stability of the program as quickly as possible to prevent system crashes? I will share my experiences with you on how to solve these problems.
Java is now very popular as one of the most popular programming languages on the Internet. Our network applications are mainly developed in Java, and are divided into three layers: client, server, and database. During the test, we found that the consumption of memory and CPU resources in a program module system increased sharply, increasing until java. Lang. outofmemoryerror occurred. After analysis, Java Memory leakage is the main cause of system damage. Here we will share with you the Java Memory leakage detection and processing solutions we encountered during the development process.

This article first introduces Java memory management and causes of Java Memory leakage.

1. How Java manages memory

To determine whether memory leakage exists in Java, we must first understand how Java manages memory. Java memory management is the issue of object allocation and release. In Java, memory allocation is done by the program, and the memory release is done by the garbage collection (GC). programmers do not need to call functions to release the memory, however, it can only recycle the space occupied by objects that are useless and no longer referenced by other objects.

Java's memory garbage collection mechanism checks the reference chain from the main running objects of the program. After traversing it, it finds that the isolated objects that are not referenced are used as garbage collection. To release objects correctly, GC must monitor the running status of each object, including application, reference, reference, and assignment of objects. GC must monitor all objects. The object state is monitored to release objects more accurately and timely. The fundamental principle of releasing an object is that the object is no longer referenced.

In Java, GC recycles these useless objects, so programmers do not need to consider the memory leakage. Although we have several functions that can access GC, such as the system. GC () function that runs GC, according to the Java language specification definition, this function does not guarantee that the JVM garbage collector will certainly execute. Because different JVM implementers may use different algorithms to manage GC. Generally, the priority of GC threads is low. There are also many policies for JVM to call GC. Some of them start to work when the memory usage reaches a certain level, some are scheduled, some are gentle execution of GC, and some are interrupted execution of GC. But in general, we don't need to care about this.

2. What is memory leakage in Java?

The main cause of Memory leakage is that I forgot to release the memory I previously applied. If a reference to useless objects exists in the program, these objects will reside in the memory and consume the memory, because GC cannot be performed by the garbage collector to verify whether these objects are no longer needed. If an object is referenced, the object is defined as "valid activity" and will not be released. To determine that the memory occupied by an object will be recycled, make sure that the object will no longer be used. A typical practice is to set the object data member to null or remove the object from the set. However, when local variables are not needed, you do not need to explicitly set them to null because these references are automatically cleared when a method is executed.

In Java, memory leakage is the existence of some allocated objects. These objects have the following two features: first, these objects are referenced, that is, in a directed tree chart, tree branches can be connected to them. Second, these objects are useless, that is, they will not be used by programs in the future. If the objects meet these two conditions, these objects can be identified as memory leaks in Java. These objects are not recycled by GC, but occupy the memory.

Here we reference a common example. In the following code, we apply for an object cyclically and put the applied object into a vector. If we only release the object, however, because the vector still references this object, this object cannot be recycled for GC. Therefore, if an object is added to a vector, it must be deleted from the vector. The simplest way is to set the vector object to null.

Vector v = new vector (10); For (INT I = 1; I <100; I ++) {object o = new object (); V. add (o); O = NULL;} // at this time, all object objects are not released because variable v references these objects. In fact, these objects are useless, but when referenced, GC is powerless (in fact, GC thinks it is still useful), which is the most important cause of Memory leakage. Another example is provided to illustrate the Java Memory leakage. Assume that there is a log-type logger that provides a static log (string
MSG), any other class can call logger. Log (Message) to record the message content to the system log file.

The logger class has a static variable temp of Type hashmap. Every time a log (Message) is executed, first, write the message value to temp (with the current thread + current time as the key), and then delete the entry with the current thread and current time as the key from temp before exiting. Note: The current time is constantly changing. Therefore, the log cannot delete the entry written at the beginning of execution because the log deletes the entry before exiting. In this way, any string passed to log as a parameter cannot be recycled because it is referenced by the static variable temp of logger. This object persistence is what we call Java Memory leakage. In general, the main cause of Memory leakage in memory management is the object reference that is retained but never used again.

 

1: Find the memory leakage method.


Unlike the C ++ memory, the memory leakage of C ++ is caused by memory allocation to a program but no recovery. Java Memory leakage refers to the reference of some junk objects, which means that the program has referenced some objects but never used them.

In Jave, there are three types of references:

Strong reference: when the reference is null, the Java garbage collector will process it. Generally, most self-written programs are strongly referenced.

Soft reference: When the heap memory is insufficient, the Java garbage collector will process such references.

Weak reference: Jave's garbage collector recycles such references each time.

How to Use mat for analysis is provided that the android development and testing tools are fully installed. SDK and Eclipse:

1. Open eclipse

2. Select help-> install new software;

3. Add site: http://download.eclipse.org/mat/1.0/update-site/ in work with (this address may change, but the new address can be found on the official website: http://www.eclipse.org/mat/downloads.php)

4. generate. hprof file: insert the SD card (many Android programs need to insert the SD card), connect the device to the PC, and select the process to be tested in ddms of Eclipse, click the update heap and dump hprof file buttons.

The. hprof file is automatically saved on the SD card and copied to the/Android-SDK-Windows/tools directory on the PC. The file generated by ddms cannot be opened directly in mat and needs to be converted.

Run cmd to open the command line, CD to the directory where/Android-SDK-Windows/tools is located, and enter the command hprof-Conv XXXXX. hprof yyyyy. hprof, where XXXXX. hprof is the original file, yyyyy. hprof is the converted file. The converted files are automatically placed inAndroid-SDK-Windows/tools directory.

OK. Till now, the. hprof file has been processed and can be used to analyze Memory leakage.

5. Open mat:

In eclipse, choose windows> open perspective> Other> memory analysis.

6. Import the. hprof File

In the mat, click File-> open file to browse to the converted file. hprof file, and cancel off to automatically generate the report. Click dominator tree, group by package, and right-click the package class you have defined, select List objects-> with incoming references in the pop-up menu.

All the suspicious classes are listed. Right-click an item and choose path to GC roots-> exclude weak/soft references, all classes related to the program with Memory leakage will be further filtered out. Based on this, we can track a class in the code that produces leakage.

2: Related Knowledge

Android divides processes into six categories:

Foreground process (foreground): processes and some system processes currently displayed on the screen. For example, system processes such as dialer storage and Google search are front-end processes. For example, when you run a program such as a browser and the browser interface is displayed on the front-end, the browser is a foreground process (foreground), but once you press home to return to the main interface, the browser becomes a background program ). The process we do not want to terminate is the foreground process.
Visible process: visible processes are processes that are no longer on the frontend, but are still visible to users. For example, widgets, input methods, and so on are all visible processes. Although these processes are not on the frontend, they are closely related to our use and we do not want them to be terminated (you certainly do not want the clocks, weather, news, and other widgets to be terminated, they cannot be synchronized, and you do not want the input method to be terminated. Otherwise, you need to restart the input method every time you input the data)
Secondary Service (secondary server): Some services currently running (major services, such as dial-up, cannot be terminated by process management, so here we only talk about secondary services). For example: google Enterprise kit, Gmail internal storage, internal contact storage, etc. Although these services are secondary services, some system functions are still closely related. We often need them, so we hope they will be terminated.
Background process (hidden): Although the author uses the word hidden, it is actually a background process, which is a process that is usually understood to be switched to the background after startup, such as browsers and readers. When a program is displayed on the screen, the running process is the foreground process (foreground). Once we press home to return to the main interface (note that we press home instead of back ), the program resides in the background and becomes the background process ). There are multiple management policies for background processes: There are more active methods. Once the program is terminated immediately after it reaches the background, this method will increase the program running speed, but it cannot be restarted; there are also relatively negative ways to retain as many background programs as possible. Although it may affect the running speed of a single program, the speed will be improved when the started program is started again. Here, you need to find a balance point based on your usage habits.
Content Provider: content provided by other programs, such as calendar supply nodes and mail supply nodes. When terminating a process, such programs should have a higher priority.
Empty: a process that runs without anything. Some programs, such as BTE, still reside in an empty process after the program exits, no data is running in this process, which usually increases the next Startup speed of the program or records some historical information of the program. This part of the process should undoubtedly be terminated first. The system evaluates the importance of processes and presents the importance in the value "oom_adj" to each process. (The system determines which processes need to be terminated based on "oom_adj, generally, if the value of "oom_adj" is greater, the process may be terminated by the system)
The "oom_adj" value of the foreground program is 0, which means that it will not be terminated by the system. Once it is inaccessible, it will get a higher "oom_adj ", the author assumes that the value of "oom_adj" is determined based on the position of the software in the LRU list;
Unlike Linux, Android has a unique set of process management modules. This module is more customizable and can be used to determine process management policies based on the range of "oom_adj" values, for example, you can set "when the memory is less than X, end the process with" oom_adj "greater than Y ". This gives you more options for writing process management scripts.

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.