Will the local handler with postDelayed receive garbage collected before the runnable call

This is a safe thing. Of course, this is convenient, but can a handler collect garbage before running runnable?

public void dodelayed()
{
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run()
        {
            //do something
        }
    }, 50);
}
+3
source share
1 answer

No, this is not GCed. It is just perfect to do it this way.

A bit more explanation to avoid confusion:

Although you do not store the link to the handler, it is stored somewhere else. In the sendMessageAtTime method , which is called internally postDelayedbefore the handler places the message in the message queue, it assigns itself to the targetmessage field , so there is still a reference to the handler, and it is not GCed:

public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
    //...
    if (queue != null) 
    {
        msg.target = this; // here the reference to the handler is assigned 
        sent = queue.enqueueMessage(msg, uptimeMillis);
    }
    //...
}
+8
source

All Articles