Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a local Handler with postDelayed get garbage collected before the runnable is called

Tags:

java

android

Is the following a safe thing to do. It sure is handy, but can the Handler get garbage collected before the runnable runs?

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

        @Override
        public void run()
        {
            //do something
        }
    }, 50);
}
like image 844
Kevin Westwood Avatar asked Jan 17 '23 19:01

Kevin Westwood


1 Answers

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

Little longer explanation, to avoid confusions:

Although you don't store the reference to the handler, it is stored somewhere else. In the method sendMessageAtTime, which is called from inside postDelayed, before the handler puts the message in the message queue, it assigns itself in the target field of the message, 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);
    }
    //...
}
like image 152
MByD Avatar answered Jan 30 '23 21:01

MByD