How/when is a Handler garbage collected?
<p>Inside a class of mine I have the following code:</p>

<pre><code>mHandler = createHandler();

private Handler createHandler() {
    return new Handler() {
        public void handleMessage (Message msg) {
            update();
            if (!paused) {
                sendEmptyMessageDelayed(0, 300);
            }
        }
    };
}
</code></pre>

<p>The documentation says:</p>

<p><a href="http://developer.android.com/reference/android/os/Handler.html">http://developer.android.com/reference/android/os/Handler.html</a></p>

<blockquote>
  <p>Each Handler instance is associated with a single thread and that thread's message queue</p>
</blockquote>

<p>So if I understood correctly the Handler is not garbage collected as long as the application thread is running, is that correct? </p>

<p>In my specific example since the Handler is an anonymous inner class it has an implicit reference to the enclosing Object and the whole hierarchy of objects that is pointed by it. This looks to me like a recipe for memory leaking.</p>

<p>Btw, I can make the Handler stop sending messages(that's why I have the <code>if (!paused)</code>) but this won't make it be GCed, right?</p>

<p>So is there a way to remove the Handler from the message queue and get it to be GCed? </p>
