Memory leak caused by Handler

Look at the following code, it will cause a memory leak

public class HandlerActivity extends Activity {
	//may cause memory leak
	private final Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			//...
		}
	}
}

Handler works with Looper and MessageQueue. In Android, after an application starts, the system will create a main thread by default.

The Looper object of the service, the Looper object is used to process all Message objects of the main thread , and its life cycle runs through the life cycle of the entire application. exist

Handlers used in the main thread are bound to this Looper object by default. When a Handler object is created in the main thread, it is immediately associated with the main thread Looper

The MessageQueue of the object, at this time, the Message objects sent to the MessageQueue will hold a reference to the Handler object, so that in the 

The Looper can only call back to the handleMessage method of the Handler when it processes the message . Therefore, if the Message has not been processed, then the Handler

Objects will not be garbage collected. In the above code, the instance of Handler is declared as an inner class of the HandlerActivity class.

In the Java language, an anonymous class inside a non-static class will hold an implicit reference to the outer class, which may cause the outer class to not be garbage collected .

So in the end, because the Message in the MessageQueue has not been processed, it will hold a reference to the Handler object instead of a static Handler 

The object will hold a reference to the external class HandlerActivity, which cannot be garbage collected, resulting in a memory leak.

Solution:

1° When using Handler in a child thread, you need to create a Looper object yourself. The life cycle of this Looper object is the same as that of a general java object , so

There is no problem with this usage.

2° Declare Handler as a static inner class. As mentioned earlier, the static inner class will not hold the reference of the outer class , so it will not cause memory leaks.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324815096&siteId=291194637