Skip to content Skip to sidebar Skip to footer

Is This Runnable Safe From Memory Leak?

I am a total beginner in Java and have created a simple Java Android snippet where in a Runnable after 1,5 seconds I change the TextView from Hello World to Hola Mundo. It works fl

Solution 1:

I have a doubt if there's absolutely no memory leak whenever device orientation occurs.

It could be. For 1.5seconds. After the queue is emptied the handler can be garbage collected, and also the old Activity. To be safe override onPause, and call handler.removeCallbacks(null); to clear the Handler's queue

Solution 2:

I think your code is leak free if you use :

privatestaticHandlerh=newHandler(); 

or

txtview.postDelayed(newWeakRunnable(txtview),1500);

because you have stored the view as a WeakReference. the method:

txtview.postDelayed(newWeakRunnable(txtview),1500);

simply call main handler of the UI thread so if the activity is destroyed the view is null and the runnable dose nothing.

also because of the weakreference the activity can be garbage collected because there is no strong reference to it.

Solution 3:

h.postDelayed(new WeakRunnable(txtview),1500); I think it will be blocking UI Thread. here is a good sample for memory leak. https://github.com/badoo/android-weak-handler

Solution 4:

Please do this, otherwise you will be blocking UIThread and it is not recommended. To do this, you can also use a TimerTask, check it here: http://developer.android.com/reference/java/util/TimerTask.html

import android.widget.TextView;
import android.util.Log;
import java.lang.ref.WeakReference;

publicclassHelloWorldActivityextendsActivity
{
    privateHandlerh=newHandler();
    privatestatic TextView txtview;

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtview = (TextView) findViewById(R.id.mainview);        

        h.postDelayed(newRunnable() {
           @Overridepublicvoidrun() {
              changeText();
           }
        }, 1500);
    }

    publicvoidchangeText(){
       txtview.setText("Hola mundo.");
       h.removeCallbacksAndMessages(null);
    }          

}

By the way, you can change orientation in your emulator this way: Ctrl+F12

Post a Comment for "Is This Runnable Safe From Memory Leak?"