The last iteration of this year is finally over, pull out the unfamiliar things in the process and learn to summarize the nature of the memory leak is: "A (huge) short life cycle object is a reference to a long life cycle (the asynchronous life cycle) of the object held" this thing is divided into two parts
- Get an object with a (huge) short life cycle
- This "huge short-life-cycle object" is most likely to be "Activity" in Android.
- The easiest way to get it unconsciously is to " implicitly automatically hold strong references to external classes by non-static inner classes"
- Assigning this object to a long life cycle object
- This has some common routines.
- Routine one: assigning directly to a static member of a class
- This static member's life cycle is as long as the application, which causes the static instance to hold a reference to the activity, causing the activity's memory resource not to be recycled properly
- Routine Two: An anonymous internal handler form holds the acitivity, then the message holds the handler, and the last long life cycle of looper holds this message
- Handler belongs to the TLS (Thread Local Storage) variable, and the life cycle and activity are inconsistent
- When the Android app starts, it creates a Looper object for the main thread of the UI, and Looper implements a simple message queue, one for processing the message object inside. The main thread Looper object exists throughout the application life cycle.
- When handler is initialized in the main thread, the handler is associated with the Looper message queue, and a message sent to the messages queue references the handler object that sent the message
- As long as the message sent by handler has not been processed, the message and the handler object that sent it will be held by the thread MessageQueue
- When this activity exits, there is an unhandled message in the message queue, or a message is being processed, and the message in the messages queue holds a reference to the Mhandler instance, and Mhandler holds a reference to the activity. So the memory resources of the activity cannot be reclaimed in time, causing a memory leak
- Routine three: An anonymous internal runnable holds acitivity, and then this runnable has a time-consuming task, the life cycle of this time-consuming task is longer than acitivity
- Asynchronous tasks Asynctask and runnable are an anonymous inner class, so they have an implicit reference to the current activity
- The main reason for a memory leak caused by threads is that the thread life cycle is not controllable. For example, a thread is an internal class of activity, and a reference to the activity is saved in the thread object, and the thread object is not destroyed when the thread's run function takes longer to end, so the old activity that it references is not destroyed, so there is a memory leak.
- One feature of thread in Java is that they are directly referenced by GC root, which means that the Dalvik virtual machine has strong references to all activated threads, causing the GC to never reclaim these thread objects. Unless the thread is manually stopped and set to null or the user directly killed the process operation. So when using a thread, be sure to consider stopping the thread and releasing it in time when the activity exits
- Routine Four: Passing this object into an asynchronous thread
So the solution is (the following is OK if you block one place)
- Don't get an object of a (huge) short life cycle, if you don't need it.
- For example, the easiest way to get activity unconsciously is to " implicitly automatically hold strong references to external classes by non-static inner classes."
- In order not to allow internal classes to automatically hold strong references to external classes, the original "non-static inner class or anonymous inner class" is rewritten as "Static inner class", that is, to separate out and add a static
- Or do not use an inner class that pulls out to be an external class
- (In this case, the external environment is not directly used in the inner class (calling the variables and methods of the external class), and if it is to be used, it is passed through the constructor method)
- (This avoids the internal class's automatic uncontrolled holding of all external environments, allowing only internal classes to use resources from the specified external environment)
- Use weak references when you need to get an object with a (huge) short life cycle
- If you must hold a acitivty reference, change the reference to a weak reference
- However, in the case of "non-static inner class or anonymous inner class", it needs to be rewritten as "Static inner class", because it is necessary to discard the object of automatic holding acitivity, and then pass the activity through the construction method to change the acitivity reference to a weak reference.
- Do not assign a value to a long life-cycle object, if you can.
- So there's no need to use static variables anywhere.
- But the front hander and Runnable there is no way, can not change
- Control the life cycle of objects of this long life cycle, if possible
- For example, a static variable can be emptied when it is emptied.
- Replace "(huge) Short life cycle Objects" with "(huge) long life cycle objects"
So we can launch most of the scene (from the above routines directly can get several scenes)
- Routine One: A singleton holds an external reference
- Occurrence scene
- Network Access Library Volleycreator Single instance holds external context
- Toastutil in a toast single case holds external context
- Newmsgreceiver member variable observers in a singleton is deposited into an external activity reference
- Reason:
- The static characteristics of a single case make the life cycle of the singleton as long as the life cycle of the application
- Workaround:
- Suitable for use method five
- Single case reference context to note the context of the life cycle, the general context can use ApplicationContext, for the singleton member variable attention in Ondestory remove the reference, such as observer mode unregister.
- Or just take applicationcontext in a single case.
- Routine one: Static variables of activity hold their own references
- This is the method we used to use when the scene "one acitivity kills the other acitivity in front"
- Solutions
- You can use method four: Empty this static variable at OnDestroy
- Or do not use this method to kill activity, using Eventbus
- Routine one: Creating a static instance with a non-static inner class
- It's easy to understand that you have this object holding the context, and then assigning the object to a static variable, the context directly leaks
- For example: In active activity, in order to avoid creating the same data resource repeatedly, it appears:
- A singleton of a non-static inner class is created inside the activity, and the singleton data is used each time the activity is started, which avoids duplication of resources, but it can cause a memory leak
-
- public class Mainactivity extends Appcompatactivity {
- private static Testresource mresource = null;
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- if (Mresource = = null) {
- Mresource = new Testresource ();
- }
- //...
- }
- Class Testresource {
- //...
- }
- }
|
- This must use static variables, and do not know when to release, the solution is method one, directly to the non-static internal class to the static.
- Routine two: non-static handler holding external context references
- This is because handler needs to hold activity, so use method two
- Then specifically:
- Creates a static handler inner class, and then uses weak references to objects held by handler so that objects held by handler can be reclaimed at collection time
- This avoids an activity leak, but the message queue of the Looper thread is still a message that is likely to be processed, so a better practice is to remove messages from the message queue when the activity is destroy or stop.
- In addition, you can also use the Open Source Library Weakhandler, a handler to prevent memory leaks, see banner source Weakhandler.java
-
- public class Mainactivity extends Appcompatactivity {
- Private MyHandler Mhandler = new MyHandler (this);
- Private TextView Mtextview;
- private static class MyHandler extends Handler {
- Private weakreference<activity> reference;
- Public MyHandler (activity activity) {
- Reference = new weakreference<> (activity);
- }
- @Override
- public void Handlemessage (Message msg) {
- if (Reference! = null && reference.get () = null) {
- Activity activity = Reference.get ();
- Activity.mTextView.setText ("");
- }
- }
- }
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- Mtextview = (TextView) Findviewbyid (R.id.textview);
- LoadData ();
- }
- private void LoadData () {
- ... request
- Message message = Message.obtain ();
- Mhandler.sendmessage (message);
- }
- @Override
- protected void OnDestroy () {
- Super.ondestroy ();
- Use Mhandler.removecallbacksandmessages (null) to remove all messages and all runnable in the message queue
- Mhandler.removecallbacksandmessages (NULL);
- }
- }
|
- Routine three: memory leaks caused by threads
- More commonly, these two examples may have been written by everyone:
-
- new asynctask<void, Void, void> () {
- @Override
- protected void doinbackground (void ... params) {
- &N Bsp Systemclock.sleep (10000);
- return null;
-
- }.execute ();
|
- new Thread (new Runnable () {
- & nbsp @Override
- public void run () {
- Systemclock.sleep (10000);
-
- }). Start ();
|
- If the task is likely to execute for a long time, it needs to be handled, using method one or method two is ok
-
- When the activity is destroyed, you should also cancel the corresponding task Asynctask.cancel (), avoid the task in the background waste resources
- Static class Myasynctask extends Asynctask<void, Void, void> {
- Private weakreference<context> WeakReference;
- Public Myasynctask (Context context) {
- WeakReference = new weakreference<> (context);
- }
- @Override
- protected void Doinbackground (void ... params) {
- Systemclock.sleep (10000);
- return null;
- }
- @Override
- protected void OnPostExecute (void aVoid) {
- Super.onpostexecute (aVoid);
- Mainactivity activity = (mainactivity) weakreference.get ();
- if (activity! = NULL) {
- //...
- }
- }
- }
|
- Static class Myrunnable implements runnable{
- @Override
- public void Run () {
- Systemclock.sleep (10000);
- }
- }
|
- —————— Use ——————
- New Thread (New Myrunnable ()). Start ();
- New Myasynctask (This). Execute ();
|
Other routines that can cause memory leaks (in fact, the reason is also within the routines)
- Mainactivity and Homefragment Eventbus no anti-registration
- Solution: Ondestory attention to anti-registration
- Memory leaks due to resource not shutting down
- For use of resources such as Braodcastreceiver,contentobserver,file,cursor,stream,bitmap, should be closed or logged off when the activity is destroyed, otherwise these resources will not be recycled, Cause a memory leak
- Some code does not cause memory leaks, but they do not effectively and promptly release unused memory, or do not effectively use existing objects but frequently request new memory.
- Bitmap did not call recycle ()
- When the bitmap object is not in use, we should first call recycle () to free the memory and then set it to null. Because the memory space of the bitmap object is loaded, part of it is Java, Part C (because the bitmap allocation is called through JNI). and this recycle () is the memory release for part C.
- Viewholder
- When you construct Adapter, you do not use the cached Convertview, and each time you create a new converview. It is recommended to use Viewholder
- Collection Class
- The collection class if there are only methods to add elements, and there is no corresponding removal mechanism, the memory is occupied. If the collection class is a global variable (such as a static property in a class, a global map, or a static reference, or final always points to it), then there is no corresponding deletion mechanism, which is likely to cause the collection to consume only a few more memory
Some tips
- In the activity's OnDestroy method, manually set NULL for all static variables that need to be null
- Do not initialize static members at the initial time of the class. You can consider lazy initialization
- Try not to use non-static external member variables in static inner classes, use weak references as well.
- In the Java implementation process, it is also necessary to consider its object release, the best way is not to use an object, the object is explicitly assigned to NULL, such as the use of bitmap after the first call recycle (), and then null, empty the image and other resources have a direct or indirect reference to the array (using Array.clear (); array = null), etc., it is best to follow the principle of who created who released
Appendix:non-static inner classes implicitly automatically hold strong references to external classes
- This is a very easy situation, such as when you casually new an anonymous inner class will happen, such as new a clicklistener,new a runnable,new a handler, but this situation itself is not a problem, The problem is that it happens when you match other conditions.
- This is plainly the case: objects of non-static inner classes hold strong references to external objects
- Why this is so, well understood: because the internal class to be able to use the external class of resources, is through this reference implementation .
the wording of the weak citation hold (take acitivty as an example of handler holding)
| public static class MyHandler extends Handler//declares a weak reference object weakreference<mainactivity> mreference; MyHandler (mainactivity activity)//incoming activity in the constructor, creating a weak Reference object mreference = new Weakreference<mainactivity> ;(activity); public void Handlemessage (Message msg)//Before using activity, empty processing if (mreference! = null && Mreferen Ce.get () = null) Mreference.get (). Text.settext (hello Word); } }} |
variables that pass in a short life cycle to a static method (such as acitivity) do not cause a memory leak
- Scene
- For example, the static boot Acitivity method passed in the previous acitivity
- Put some common or common methods into a tool class, written in static form, if the method needs to pass a parameter (a reference to an external short life cycle object)
- Reason
- To cause a memory leak, your tool class object itself holds a reference to the incoming object! But when your business method invokes the static method of the tool class, it produces something called the method stack frame (each method call, the JVM generates a method stack frame), and when the method call is returned, the current method stack frame is ejected and released. At the end of the process, the tool class object itself does not hold a reference to the incoming object.
- Passing an object reference to a static method (not the same as a static method), at the end of the call, the tool class object itself does not refer to the incoming object. So there's no problem.
The essential causes, solutions, and operating examples of Android memory leaks