1

There is a warning if we use non-static Handler: 'handler should be static, else it is prone to memory leaks.'

I have read below links and I know what their mean.

https://stackoverflow.com/a/7909437/619424
https://stackoverflow.com/a/11336822/619424

But after read the source of Handler.java, Message.java and Looper.java, I'm confused...

In Looper.loop() method, we can see below statements:

msg.target.dispatchMessage(msg);

...

msg.recycle();

the variable msg holds a reference named target to a corresponding Handler. When a Message is proceessed by Looper, msg is dispatched to the Handler (target reference), after that, msg is recycled.

Message.recycle() method calls Message.clearForRecycle() method, in that, we see:

...

target = null;

...

target is set to null, that means, Message doesn't holds the reference to Handler. Non-static Handler will be GCed, and both Activity and Views will be GCed.

So my question is, why there might a memory leak occurs?

Community
  • 1
  • 1
chengbo
  • 5,789
  • 4
  • 27
  • 41

0 Answers0