Ext.: http://blog.chinaunix.net/uid-26930580-id-3844811.html
1 , memory leaks:
A memory leak occurs when objects such as activity, view, or drawable have long held useless references, causing the referenced object to not be recycled during GC, but for long-term use of heap space.
Simply put, it is an object reference that is retained but never used.
2 , Memory overflow:
If the application consumes all available heap space (16M to 48M), then attempting to allocate new objects on the heap causes an oom (out of Memory Error) exception, and the application crashes and exits.
3 , the difference between the two:
Simply put, memory overflow is too much memory, exceeding the range it can withstand;
A memory leak is a lot of useless references that are generated in a push space that is not recovered in time or even is not recycled.
So excessive memory leaks can cause memory overruns, forcing the program to crash and exit.
4 , four different types of references:
|
Reference name |
Strong Reference (Strong reference) |
Soft Reference (Soft reference) |
Weak Reference (Weak reference) |
Phantom Reference (Virtual Reference) |
|
Citation characteristics |
Usually we write code that is strong Ref, which corresponds to strong accessibility, and the object is recycled only if you remove the strong. |
corresponding to soft accessibility, the object is persisted as long as there is enough memory, until the memory is found to be tight and no strong ref is collected. Generally available to implement caching, |
Weaker than soft ref, reclaims objects immediately when no strong ref is found and doesn't have to wait until memory is tight |
No objects are kept in memory at all, and you can only use phantom ref itself. Typically used to perform a special cleanup process after entering the Finalize () method |
|
Citation method |
|
Through Java.lang.ref.
SoftReference class implementation |
Implemented by Java.lang.ref.WeakReference and JAVA.UTIL.WEAKHASHMAP classes |
Implemented through Java.lang.ref.PhantomReference |
5 , holding a leak caused by a context reference.
In Android applications, many operations use the context object, but most of them are used to load and access resources.
This is why all display controls require a context object as a parameter to the constructor method.
There are two kinds of context objects commonly used in Android applications: Activity and application.
The common practice when a class or method requires a context object is to use the first as the context parameter.
But this means that the View object keeps a reference to the entire activity, so it keeps a reference to everything in the activity,
That is, the entire view structure and all of its resources can not be recovered in a timely manner, and the long-term activity of the reference is relatively covert.
When the screen orientation changes, the Android system default is to destroy the current activity, and then create a new activity, the new activity will show just the state.
During this process, the Android system reloads the resources used by the UI.
It is now assumed that there is a larger picture of the bitmap type in the application, and it takes more time to reload the picture each time it is rotated.
To improve the speed of activity creation when the screen rotates, the simplest method is to use static variables.
This code executes quickly, but at the same time it is wrong: writing this will always keep a reference to the activity.
When a Drawable object is attached to a view, the view is the equivalent of a callback (reference) to the Drawable object.
In the code snippet above, it means that there is a referential relationship between drawable and TextView.
And TextView himself has a reference to the activity (context object), and this activity refers to quite a lot of things.
There are two simple ways to avoid memory leaks caused by referencing a context object.
The first approach is to avoid the context object from exceeding its scope.
The example above shows the case of a static reference, but inside the class, implicitly referencing the outer class is the same danger.
The second method is to use the Application object. This context object exists as the application exists and does not depend on the activity's life cycle.
If you intend to keep a long-term reference to the context object, remember this Application object.
You can easily get this object by calling Context.getapplicationcontext () or activity.getapplication ().
If you need to reference activity when using static classes in activity, you should use WeakReference weak references to refer to activity.
Summarize the issues that should be noted to avoid a context leak: Try to use the context type application,
Attention to the context of the reference do not exceed its own life cycle, prudent use of the context of the "static" keyword, the context if the thread, must be in OnDestroy () in time to stop.
To prevent memory leaks, we should pay attention to the following points:
(1) Do not allow objects with long life cycles to refer to the activity context, which is to ensure that the object referencing the activity is the same as the activity itself life cycle.
(2) For objects with long life cycles, you can use the application context.
(3) Avoid non-static inner classes, use static classes as much as possible, avoid life cycle problems, and notice the life cycle changes caused by internal classes to external object references.
6 , memory leaks caused by handler communication between Threads
The most common practice when communicating between Android threads is to create a message object by holding a handler object on the target thread that receives the message, and then send that message to the target thread.
In the target thread, handler executes Handlemessage () and performs different functions according to the corresponding message.
Another approach is to execute the different function codes in the Runnable object by sending the Runnable object directly to the target thread through the handler object.
It is also possible to cause a memory leak if you are not aware of it when communicating through handler.
The MSG member variable is set to null after SendMessage completes, and handler is set to NULL before exiting the entire application.
7 , set the scope of the variable to the minimum
Minimizing the scope means faster visibility of the garbage collector. Let's give an example.
We have a variable defined at the method level, and when the method finishes executing, that is, after the control jumps out of the method, the variable will not be referenced.
This means that it can already be garbage collected. However, if the variable is class-level, the garbage collector will need to wait until all references to the class have been removed before it can be garbage collected.
It is necessary to optimize the scope of the property. Likewise this is the encapsulation principle. Minimizing the scope reduces the access to variables through the package and reduces coupling.
8 , when constructing adapter, no cached Convertview is used.
Initially, the ListView instantiates a certain number of view objects from the Baseadapter based on the current screen layout, and the ListView caches the View objects.
When you scroll up the ListView, the View object that was originally on the top list item is recycled and then used to construct the newly-appearing list item.
This construction process is done by the GetView () method, and the second parameter view convertview of GetView () is the view object of the cached list item (the cache does not have a view object when it is initialized, and Convertview is null.) )。
It can be seen that if we do not use Convertview, but each time in GetView () to re-instantiate a View object,
That is, waste of time, also cause memory garbage, to increase the pressure on garbage collection, if garbage collection is too late, the virtual machine will have to allocate more memory to the application process, causing unnecessary memory expenditure.
9 , bitmap recovery and empty.
The Bitmap object does not call recycle () to free memory when it is in use, and sometimes we manipulate the Bitmap object manually.
If a bitmap object compares memory and the bitmap object is not in use, we should call recycle () to free memory before it is set to null.
Although recycle () from the source, call it should be able to immediately release Bitmap's main memory, but the test results show that it does not immediately release memory.
But I should still be able to greatly accelerate the release of bitmap's main memory.
Ten , a memory leak caused by a resource object not being closed.
Resource objects such as (cursor,file files, etc.) often use some buffering, we should close them in time when we are not in use, so that their buffers can recover memory in time.
Their buffering exists not only in the Java Virtual machine, but also outside the Java Virtual machine.
If we simply set its reference to null without shutting them down, it often causes a memory leak.
Because there are some resource objects, such as Sqlitecursor (in the destructor Finalize (), if we do not close it, it itself will be close () closed),
If we don't shut it down, the system will turn it off when it recycles it, but it's too inefficient.
Therefore, when the resource object is not in use, it should call its close () function, turn it off, and then set to null.
Be sure that our resource objects are closed when our program exits.
The process of querying the database is often done, but there are often cases where the cursor is not closed after it has been used.
If our query result set is relatively small, the memory consumption is not easy to find, only in the case of a large number of operations in a constant time to reproduce the memory problem, which will give future testing and troubleshooting difficulties and risks.
One , various registrations have not been canceled.
This is caused by memory leaks such that Android memory leaks are more serious than pure Java memory leaks, as some other Android programs may refer to our Anroid program's objects (such as the registration mechanism).
Even though our Android program is over, other reference programs still have a reference to an object in our Android program, and the leaked memory is still not garbage collected
。 For example, suppose we want to listen to the phone service in the system in the lock screen (lockscreen) to get some information (such as signal strength, etc.),
You can define a Phonestatelistener object in Lockscreen and register it with the Telephonymanager service.
For Lockscreen objects, a Lockscreen object is created when the lock screen needs to be displayed, and the Lockscreen object is released when the lock screen disappears.
However, if you forget to cancel the Phonestatelistener object that we previously registered when releasing the Lockscreen object, it will cause lockscreen to be garbage collected.
If the lock screen interface is constantly displayed and disappears, it will eventually cause outofmemory due to the fact that a large number of Lockscreen objects have no way to be recycled, causing the system_process process to hang out.
Although some system programs, it seems that it can be automatically unregistered (of course, not in time), but we should still clear in our program to unregister, the end of the program should be all the registration is canceled.
A , the memory leak caused by the collection container object not being cleaned up.
We usually add references to some objects in a collection container (such as ArrayList), and when we don't need the object,
It does not remove its references from the collection, so the collection will grow larger. If the set is static, the situation is even worse.
So before exiting the program, clear the contents of the collection, then set NULL, and then exit the program.
- , and the misuse of the static keyword.
When a member variable of a class is declared static, it belongs to the class and not to the object.
If we declare a large resource object (Bitmap,context, etc.) as static, then these resources will not be recycled as the object is recycled.
Always exists, so be cautious when defining member variables using the static keyword.
- , the WebView object is not destroyed.
When we do not use the WebView object, we should call its destory () function to destroy it and release its memory, otherwise its memory will not be recycled for a long time, causing a memory leak.
the , and the abuse of the GridView.
The GridView and the ListView are not implemented the same way. The GridView view is not created on-the-fly, but is all kept in memory.
For example a GridView has 100 items, although we can only see 10 items, but in fact the entire 100 items are in memory.
So before the application exits, the GridView and adapter are all null.
Android memory leaks