Android Memory leak Finishing

Source: Internet
Author: User
Tags message queue

Android Memory leak Finishing

Reference Documents: 1, https://www.ibm.com/developerworks/cn/java/l-JavaMemoryLeak/#icomments

2, http://blog.csdn.net/anxpp/article/details/51325838

3, http://www.jianshu.com/p/ac00e370f83d

4. memory Management in HTTP://WWW.JIANSHU.COM/P/C5AC51D804FA theory JAVA

To understand memory leaks in Java, you first need to know how memory in Java is managed.
In Java programs, we typically use new to allocate memory to objects, which are on the heap (Heap).
Let's look at an example:
public static void Main (String args[]) {
Object Object1 = new Object ();//obj1
Object object2 = new Object ();//obj2
Object2 = Object1;
//... At this point, obj2 can be cleaned up.
}

Java uses a forward-graph approach to memory management:



In the map, we call the obj1 is up to, OBJ2 is not up to, obviously can be cleaned up.
The release of memory, or the cleanup of unreachable objects, is determined and performed by GC, so the GC monitors the status of each object, including requests, references, references, and assignments. The fundamental principle of releasing objects is that objects are no longer used:
• A null value was given to the object, which was never invoked before.
• The other is to give the object a new value, so that the memory space is reallocated.

Generally, it is considered that the cost of allocating objects on the heap is relatively high. But the GC optimizes this operation: in C + +, the allocation of a piece of memory on the heap, will find a suitable memory to allocate, if the object is destroyed, this memory can be reused; in Java, you want a long tape, each assigning a new object, The Java heap pointer moves backwards to areas that have not been allocated. Therefore, the Java allocation of memory efficiency, comparable to C + +.
But there is a problem with this way of working: If you frequently request memory, resources will be depleted. The GC then comes in and it reclaims the space and makes the objects in the heap more compact. In this way, there will always be enough memory space to allocate.
Reference count when GC cleanup: reference count +1 When a reference is connected to a new object, and when a reference leaves the scope or is set to NULL, the reference count -1,GC finds the count to be 0 o'clock and reclaims the memory it occupies. This overhead occurs throughout the lifecycle of the referencing program and does not handle the case of circular references. So this is just a way to illustrate how the GC works without being applied by any Java virtual machine

Memory Leaks

Memory leaks in Java, broadly and generally speaking, is: the object can no longer be used by the memory can not be recycled, that is, memory leaks.
Examples of source code in Java to avoid memory leaks:

Public E-Remove (int index) {
if (index >= size)
throw new Indexoutofboundsexception (Outofboundsmsg (index));
modcount++;
E OldValue = (e) elementdata[index];
int nummoved = size-index-1;
if (nummoved > 0)
System.arraycopy (Elementdata, index+1, Elementdata, Index,
nummoved);
Elementdata[--size] = null; Clear to let GC does its work
return oldValue;
}


instance Static Activity

A static activity variable is defined in the class, and the currently running activity instance is assigned to this static variable.
If this static variable is not emptied at the end of the activity lifecycle, it causes a memory leak. Because the static variable runs through the lifecycle of the application, the exposed activity will always exist in the application process and will not be reclaimed by the garbage collector.

static activity activity;
void Setstaticactivity () {
activity = this;
}

View Sabutton = Findviewbyid (R.id.sa_button);
Sabutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Setstaticactivity ();
Nextactivity ();
}
});

Solution
A weak reference does not prevent the memory release of an object, so the object can be reclaimed even if there is a weak reference.
private static weakreference<mainactivity> activityreference;

void Setstaticactivity () {
Activityreference = new Weakreference<mainactivity> (this);
}

Or, at the end of use, manually release.


Static views
Similar situations can occur in singleton mode, and it is useful to save an instance in memory if the activity is often used. As mentioned earlier, it is quite dangerous and unnecessary to force the life cycle of an activity to be prolonged, and it cannot be done in any way.
Special case: If a view initialization consumes a lot of resources and remains unchanged during an activity lifecycle, it can be static and loaded into the view hierachy, such that resources should be released when the activity is destroyed.

static view;
void Setstaticview () {
View = Findviewbyid (R.id.sv_button);
}

View Svbutton = Findviewbyid (R.id.sv_button);
Svbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Setstaticview ();
Nextactivity ();
}
});

Solution
Same static activity

Inner Classes
Continue, assuming that there is an internal class in the activity, which can improve readability and encapsulation. Will be like we create an inner class, and hold a reference to a static variable, congratulations, memory leaks are not far away from you.
One of the advantages of an inner class is that it can access the external class, which, unfortunately, causes the memory leak because the inner class holds a strong reference to the external class instance.
private static Object inner;

void Createinnerclass () {
Class Innerclass {
}
Inner = new Innerclass ();
}

View Icbutton = Findviewbyid (R.id.ic_button);
Icbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Createinnerclass ();
Nextactivity ();
}
});

Solution
Private Object inner; Does not use a static object.

Anonymous Classes
Handler,threads,timertask

Similarly, anonymous classes maintain references to external classes. So memory leaks are easy to happen when you define anonymous Asynctsk in activity
。 When an asynchronous task performs a time-consuming task in the background, the activity is unfortunately destroyed, and the activity instance held by the Asynctask is not reclaimed by the garbage collector until the asynchronous task ends.
void StartAsyncTask () {
New Asynctask<void, Void, void> () {
@Override protected void doinbackground (void ... params) {
while (true);
}
}.execute ();
}

Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
View Aicbutton = Findviewbyid (R.id.at_button);
Aicbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
StartAsyncTask ();
Nextactivity ();
}
});


In the same way, define anonymous runnable, handler execution with anonymous classes. The runnable inner class holds an implicit reference to the external class, is passed to the handler message Queue MessageQueue, and the activity instance is not destroyed until the message messages are processed, resulting in a memory leak.
void Createhandler () {
New Handler () {
@Override public void handlemessage (message message) {
Super.handlemessage (message);
}
}.postdelayed (New Runnable () {
@Override public void Run () {
while (true);
}
}, Long.max_value >> 1);
}


View Hbutton = Findviewbyid (R.id.h_button);
Hbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Createhandler ();
Nextactivity ();
}
});
We again show memory leaks through thread and timertask.
void Spawnthread () {
New Thread () {
@Override public void Run () {
while (true);
}
}.start ();
}

View TButton = Findviewbyid (R.id.t_button);
Tbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Spawnthread ();
Nextactivity ();
}
});

As long as an instance of an anonymous class, whether on a worker thread or not, holds a reference to the activity, causing a memory leak.
void Scheduletimer () {
New Timer (). Schedule (new TimerTask () {
@Override
public void Run () {
while (true);
}
}, Long.max_value >> 1);
}

View Ttbutton = Findviewbyid (R.id.tt_button);
Ttbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Scheduletimer ();
Nextactivity ();
}
});

Solution
Static inner classes do not hold references to external classes.

private static class Nimbletask extends Asynctask<void, Void, void> {
@Override protected void doinbackground (void ... params) {
while (true);
}
}

void StartAsyncTask () {
New Nimbletask (). Execute ();
}
Or, at the end of the lifecycle, break or release the use of the associated anonymous class.

Sensor Manager
Finally, system services can be obtained by context.getsystemservice (int name). These services work in their respective processes, helping to apply background tasks and handle hardware interactions. If you need to use these services, you can register the listener, which causes the service to hold a reference to the context, which can cause a memory leak if you do not unregister these listeners when the activity is destroyed.
void Registerlistener () {
Sensormanager Sensormanager = (sensormanager) getsystemservice (Sensor_service);
Sensor Sensor = Sensormanager.getdefaultsensor (Sensor.type_all);
Sensormanager.registerlistener (this, sensor, sensormanager.sensor_delay_fastest);
}

View Smbutton = Findviewbyid (R.id.sm_button);
Smbutton.setonclicklistener (New View.onclicklistener () {
@Override public void OnClick (View v) {
Registerlistener ();
Nextactivity ();
}
});

Solution
Unregister the listener at the end of the activity


Private Sensormanager Sensormanager;
Private Sensor Sensor;

@Override
public void OnDestroy () {
Super.ondestroy ();
if (sensor!= null) {
Unregisterlistener ();
}
}
void Unregisterlistener () {
Sensormanager.unregisterlistener (this, sensor);
}


Tips:android Studio Memory Leak tool


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.