Wirelessly memory leaks

Source: Internet
Author: User

Because Android is based on the Java language, let's take a look at the memory leaks in Java, and then talk about memory leaks in Android.

A memory leak in Java:

Memory leaks in Java mainly refers to the memory allocated in the heap, when it is not necessary, but still retain the reference to access it, resulting in GC recovery can not be collected in a timely manner (about GC recycling does not do too much), the most important reason for this situation is that the long life cycle of objects holding short life cycle object references, objects that lead to short lifecycles are no longer needed but cannot be recycled by GC, leading to memory leaks. The main cases include the following:

1 A static instance of a non-static inner class is created in a class, as follows:

public class outer{      static Inner inner= null;               void DoSomething ()   {//do something   }    class Inner     {        void dosomething ()        {           System.out.println ("dosth.");}}    
In the preceding code, when an instance of an external class outer is first created, the inner class inner (because it is static decorated) is automatically loaded, and the inner class inner holds a reference to the outer class outer. And the life cycle of the inner class inner is obviously the same as the life cycle of the entire program (which is modified by static), so when the external class is not needed, because inner holds the outer reference, the outer cannot be recycled by the GC, resulting in a memory leak.


2 objects added using the collection framework in Java are not cleared when not in use

If we add a reference to some object to the collection, and when we do not need the object, if we do not remove its reference from the collection, but simply use it to assign NULL, let the GC be recycled (and in fact the GC is not recycled), the code is as follows:

Vector v = new vector (10);  for (int i = 1; i <, i + +) {Object o = new Object ();  V.add (o);  o = null; }
In the code above, we constantly produce a new object object in a For loop, and then add it to the vector of the collection, and then set the object's reference to null (after it is meant to be null and let the GC recycle), but in fact the GC is not recycled, Because although the reference to the object is empty, there are still other reference paths to find the object, which is found in the Vector collection object, that is, although the O reference is already empty, the object object still has other references that can be accessed, so the GC It cannot be released. If after this loop the object object has no effect on the program, we assume that the Java program has a memory leak.

To resolve this leak, you need to remove the object from the collection by calling the Remove () method when the object does not need to be used.


3 unreasonable use of single-case mode

In fact, this situation is very similar to the first case because of a memory leak caused by the static keyword. The code is as follows:

Lazy Singleton class. Instantiate yourself when you first call the public class Singleton {    private Singleton () {}    private static Singleton single=null;< C2/>public static Singleton getinstance () {         if (single = null) {Single               = new Singleton ();         }          return single;    }}
You can see that the singleton pattern class is static decorated, so the life cycle of the class is the same as the entire program life cycle, so it is easy to cause a memory leak.


4 database connection, network connection (socket) and IO connection not using the close () method to close the connection when not in use

This is a situation where it is important to use the close () method to close a resource when it is not needed.


5 Modify the parameter value of the object in HashSet, and the parameter is the field that computes the hash value:

This situation is very similar to the second situation, because in the second case we have discussed the key to avoiding a memory leak when using the Java Collection Framework is to remove the object from the collection when it is not needed.

However, when an object is stored in the HashSet collection, it is not possible to modify those fields in the object that participate in the hash value, otherwise the modified hash value of the object will be different from the hash value originally stored in the HashSet collection, in which case Even if the Contains method uses the object's current reference as a parameter to retrieve an object in the HashSet collection, the result of the object cannot be found, which also results in the inability to remove the current object from the HashSet collection, causing a memory leak.


Memory leaks in two android:

Because Android is based on the Java language, there are many things that are similar to the Java memory leaks described above.

1) Be aware of activity leaks

In general, the leakage of activity is the most serious problem in memory leak, it occupies a lot of memory, the impact of a wide range, we need to pay special attention to the following two scenarios caused by activity leaks:

Internal class references result in activity leaks

The most typical scenario is an activity leak caused by handler, and if there are deferred tasks in handler or if the queue of tasks waiting to be executed is too long, it is possible that the activity will leak because handler continues to execute. The reference chain at this time is Activity, Handler, Message, MessageQueue, Looper. To solve this problem, you can execute the message in the Remove handler message queue with the Runnable object before the UI exits. or use static + WeakReference to achieve a referential relationship between the disconnected handler and the activity.

Activity context is passed to other instances, which can cause itself to be referenced and leak.

Internal classes are caused by leaks that occur not only in the activity, but in any other internal class where there is a need for special attention! We can consider using the static type's inner classes as much as possible, while using the weakreference mechanism to avoid leaks that occur as a result of mutual references.


2) Consider using application context instead of activity context

For most situations where the activity context is not required (the context of dialog must be the activity context), we can all consider using application context instead of the activity context , so you can avoid inadvertent activity leaks.


3) When constructing adapter, no cached Convertview is used

To construct the baseadapter of a ListView, for example, a method is provided in Baseadapter:


Public View GetView (int position, Viewconvertview, viewgroup parent)


To provide the ListView with the View object that each item needs. 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 the GetView () to re-instantiate a View object, will be wasted memory resources, will make memory occupy more and more.


4) Note the logoff of the listener


There are many listeners in the Android program that need register and unregister, and we need to make sure that the listeners are unregister at the right time. Manually add the listener, need to remember to remove this listener in time.

5). Memory leaks due to resource object not shutting down

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.

Therefore, when the resource object is not in use, it should call its close () function, close it, and then set it to null. Be sure that our resource objects are closed when our program exits.

The following is a demonstration of the error code and the correct code:

cursor cursor = getcontentresolver (). Query (URI ...); if (Cursor.movetonext ()) {...}  Correct code: CURSOR cursor = NULL;  try {cursor = Getcontentresolver (). Query (URI ...);  if (cursor! = NULL &&cursor.movetonext ()) {...}  } finally {if (cursor! = null) {try {cursor.close (); } catch (Exception e) {//ignore This}}}


Bitmap object does not call recycle () to free memory when it is in use

While in most cases we will increase the caching mechanism for bitmap, some of the bitmap need to be reclaimed in a timely manner. For example, a relatively large bitmap object that is temporarily created, after being transformed to get a new bitmap object, should call the Bitmap.recycle () method to reclaim the original bitmap as soon as possible, which frees up the space occupied by the original bitmap faster.

Special attention is given to the CreateBitmap () method provided in the bitmap class:


The bitmap returned by this function may be the same as the source bitmap, and at the time of collection, it is necessary to check whether the source bitmap is the same as the return bitmap reference, and only if the source can be executed in unequal circumstances. The Recycle method of bitmap.


Ok above is I understand about wirelessly memory leak knowledge, in addition, we recommend you look at: http://www.jb51.net/article/77899.htm, in the form of code in detail several memory leaks and solutions. If you feel good, remember to top it.

Wirelessly memory leaks

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.