Memory leak: Refers to the memory is not the GC's timely recovery, resulting in excessive memory consumption, resulting in program crash, that is often said Oom.
One, static
Let's take a look at the following code
public class DBHelper {
private static dbhelper db= null;
Private DBHelper () {
} public
static DBHelper getinstance (context context) {
if (bitmaputils = = null) {
s Ynchronized (dbhelper.class) {
if (db== null) {
db= new db (Context,dbname);
}}} return db;
}
Such code is common in projects, and if you are careful, you should be able to find out where the problem is. The helper holds the application of the context, and DBHelper is global, that is, when DBHelper is used in an activity, the activity is not recoverable by GC, even if the activity exits. Thus causing the activity to reside in memory all the time.
This solution is also relatively simple, the code is as follows
public class DBHelper {
private static dbhelper db= null;
Private DBHelper () {
} public
static DBHelper getinstance (context context) {
if (bitmaputils = = null) {
s Ynchronized (dbhelper.class) {
if (db== null) {
db= new db (Context.getapplicationcontext (), dbname);
}
}
return db;
}
Only need to change the context into ApplicationContext (), because ApplicationContext itself is the global.
second, non-static internal class, Handler
let's look at a piece of code
Private Handler Handler = new Handler () {
@Override public
void DispatchMessage (Messages msg) {
//message processing
}< c5/>};
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
New Thread (New Runnable () {
@Override public
void Run () {
//time consuming Operation
Handler.sendemptymessage (1);
}
}). Start ();
}
We know that non-static inner classes hold references to external classes, where the handler holds references to external activity, and when we do asynchronous time-consuming operations in the inner class of the action, if we are done at this time, The asynchronous task does not end with execution, which leads to the inability of our activity objects to be collected in time by GC, resulting in memory problems.
It's a simple problem to solve .
- Do not perform asynchronous operations in anonymous inner classes
- Using static anonymous inner classes
Most of the memory problems are due to unfortunate processing of the object lifecycle, when working with an object, we need to study the life cycle of the object carefully, and when dealing with objects that occupy large memory and have a long lifecycle, the application uses a soft reference to handle it and closes unused resources in a timely manner.
The above is the entire content of this article, I hope to help you learn.