Memory Overflow (OOM) and memory leaks---and their solutions

Source: Internet
Author: User

So what's the problem? What is memory overflow out of memories? (OOM)

The extent to which the existing data can be stored beyond its allocated memory
For example, the application of an integer, but to save it a long to save the number, that is memory overflow.

What is memory leak memories leak?

The program cannot release the requested memory space after it has requested memory.

What the hell is the matter with them?

A memory leak hazard can be ignored, but memory leaks accumulate consequences that are serious, no matter how much memory, sooner or later will be occupied by the light. Memory leak will eventually result in out of memory!

What situations often cause memory overflow?? How to solve it??
    1. When the project contains a large number of pictures, or the picture is too large

      Method 1: Zoom out of the picture

      Copy Content to Clipboard

      Code:

 BitmapFactory.Options options = new BitmapFactory.Options();  options.inSampleSize4

Method 2: Take a soft reference to the picture and do the Recyle () operation in a timely manner

Copy Content to Clipboard

Code:

new SoftReference(pBitmap);  ifnull){  if(bitmap.getnull && !bitmap.get().isRecycled()){  bitmap.getnull;  }  }

Method 3: Design and encode the complex ListView 1. Pay attention to reusing adapter inside the Convertview, and the use of holder mechanism

The above method attempt has not been successful and can be used with the lazy loading data

Copy Content to Clipboard

Code:

public  View getView (int  position, View Convertview, ViewGroup parent) {if  (Convertview = = null ) {v = minflater.inflate (resource, parent, false ); final  int   [] to = mTo; final  int   count  = to.length; final   view[] Holder = new  view[count ]; for  (int  i = 0 ; i <  Count ;  i++) {Holder[i] = V.findviewbyid (To[i]); } v.settag (holder); } else  {}} 

Method 4: Single page, toggle N-Time after OOM on screen

1. See if there are any large pictures in the page layout, such as the background map. Remove the relevant settings from the XML and set the background map in the program (in the OnCreate () method):

Copy Content to Clipboard

Code:

 Drawable bg = getResources().getDrawable(R.drawable.bg);  XXX.setBackgroundDrawable(rlAdDetailone_bg);

Note When Activity destory, bg.setcallback (null); Prevent the activity from being released in a timely manner.

2. Similar to the above method, directly load the XML configuration file into a view and put it into a container, and then call This.setcontentview (view view) directly, avoid the repeated loading of XML.

Method 5: Reuse as few code as possible while the page is switching. For example: Repeated calls to the database, repeated use of certain objects, etc...

Method 6:android Heap Memory can also define its own size and optimize the memory of the Dalvik virtual machine

Copy Content to Clipboard

Code:

 privatefinalstaticint6*1024*1024;  privatefinalstaticfloat0.75f;  VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);  VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
Memory leaks

Common code that easily causes memory leaks
(i) the query database did not close the cursor
(ii) When constructing adapter, no cached Convertview is used
(iii) Bitmap object does not call recycle () to free memory when it is in use
(iv) Releasing a reference to an object
(v) Other
Due to the limited memory available to our applications, there is a need to pay special attention to memory usage issues when writing code. The following are some common cases of improper memory usage.
(i) the query database did not close the cursor
Describe:
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.
Example code:
cursor cursor = getcontentresolver (). Query (URI ...);
if (Cursor.movetonext ()) {
... ...
}
To fix the sample 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
}
}
}
(ii) When constructing adapter, no cached Convertview is used
Describe:
To construct the baseadapter of the ListView as an example, the method is improved in Baseadapter:
Public View GetView (int position, view Convertview, 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, that is, wasting resources is also a waste of time, it will also make memory consumption more and more. The process of retrieving the View object of the list item can be viewed by the ListView:
android.widget.abslistview.java–> void Addscrapview (View scrap) method.
Example code:
Public View GetView (int position, View Convertview, ViewGroup parent) {
View view = new Xxx (...);
... ...
return view;
}
To fix the sample code:
Public View GetView (int position, View Convertview, ViewGroup parent) {
View view = null;
if (Convertview! = null) {
view = Convertview;
Populate (view, GetItem (position));
...
} else {
view = new Xxx (...);
...
}
return view;
}
(iii) Bitmap object does not call recycle () to free memory when it is in use
Describe:
Sometimes we will manipulate the bitmap object manually, if a bitmap object compares memory, when it is not in use, you can call the Bitmap.recycle () method to reclaim the memory occupied by the pixel of this object, but this is not necessary, depending on the situation. You can look at the comments in the code:
/**
* Free up the memory associated with this bitmap ' s pixels, and mark the
* Bitmap as "dead", meaning it would throw an exception if getpixels () or
* SetPixels () is called, and would draw nothing. This operation cannot is
* Reversed, so it should is called if you is sure there is no
* Further uses for the bitmap. This is a advanced call, and normally need
* Not be called, since the normal GC process would free up this memory when
* There is no more references to this bitmap.
*/
(iv) Releasing a reference to an object
Describe:
This situation is more cumbersome to describe, with two examples to illustrate.
Example A:
Suppose you have the following actions
public class Demoactivity extends Activity {
... ...
Private Handler Mhandler = ...
Private Object obj;
public void operation () {
obj = Initobj ();
...
[Mark]
Mhandler.post (New Runnable () {
public void Run () {
Useobj (obj);
}
});
}
}
We have a member variable, obj, in operation () we want to be able to post the operation that handles the obj instance to the MessageQueue of a thread. In the above code, even if the thread mhandler is using the object referenced by obj, the object will not be garbage collected because Demoactivity.obj still retains a reference to the object. So if you no longer use this object in Demoactivity, you can release the object's reference at [Mark], and the code can be modified to:
... ...
public void operation () {
obj = Initobj ();
...
Final Object o = obj;
obj = null;
Mhandler.post (New Runnable () {
public void Run () {
Useobj (o);
}
}
}
... ...
Example B:
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 the Lockscreen. Register it with the Telephonymanager service at the same time. 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.
In short, when an object A with a shorter life cycle has its reference by a long-life object B, at the end of A's life cycle, a reference to A is cleared in B.
(v) Other
The most typical use of Android applications is to be aware of the need to release resources in the life cycle of the activity, in the OnPause (), OnStop (), OnDestroy () methods, in the case of the appropriate release of resources. Since this is a very basic situation, it is not detailed here to see the official documentation on the activity life cycle to determine when resources should be released.

The article refers to the following online information, summarized and collated, thank you very much, hereby posted

http://android.chinatarena.com/jsfx/1571.html#6d

http://blog.csdn.net/com360/article/details/6682409

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Memory Overflow (OOM) and memory leaks---and their resolution

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.