1

I read the article How to Leak a Context: Handlers & Inner Classes, and now I have got a question. If I pass mHandler as a parameter to another thread to send messages from that thread to the main thread, will it cause memory leaks?

SampleActivity

public class SampleActivity extends Activity {

    /**
     * Instances of static inner classes do not hold an implicit reference to
     * their outer class.
     */
    private static class MyHandler extends Handler {
        private final WeakReference<SampleActivity> mActivity;

        public MyHandler(SampleActivity activity) {
            mActivity = new WeakReference<SampleActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SampleActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }

    private final MyHandler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Run a thread (authentication, synchronization, etc.)
        // Later the user might press the Home button, the Back button, or make a call
        new MyThread(mHandler).start();
    }
}

MyThread

public class MyThread extends Thread {

    private final Handler handler;

    public MyThread(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        // A long operation

        // I'm done
        handler.sendEmptyMessage(1);
    }

}
Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138
  • this link may be helpful - http://stackoverflow.com/questions/11278875/handlers-and-memory-leaks-in-android#11336822 – fada21 Sep 11 '14 at 11:17
  • @fada21, no. That's what I started with. The only one difference between my question and the answer on http://stackoverflow.com/questions/11278875/handlers-and-memory-leaks-in-android#11336822 it that they use a fragment instead of an activity. – Maksim Dmitriev Sep 11 '14 at 11:28

2 Answers2

3

If MyThread is a static or external class, it can't cause leaks. There is no any non-weak references to activity.

konmik
  • 3,150
  • 19
  • 15
2

It looks ok. I don't see any object holding link to Activity (WeakRef is ok as it can be GCed). I don't see potential leaks here ;)

fada21
  • 3,188
  • 1
  • 22
  • 21
  • I was not right, my mistake, sorry :) WeakRef + static seems ok, only MyThread and MyHdandler are unreachable for GC. – dilix Sep 11 '14 at 12:26