non-static Handler class

1,048 views
Skip to first unread message

Ubuntu guy

unread,
Aug 31, 2011, 4:07:45 AM8/31/11
to android-platform
Hello,

I happened to come across a warning in a debug build,

The following Handler class should be static or leaks might occur:
<name of the class>

I tried to recreate this by having a non-static inner class extending
from Handler and created an instance of it as a member variable of the
outer class (Activity), making sure that the life of the member is
tied to the the life of the containing object (instance of activity).
I had a fininalize method in the handler and it was invoked. So i
don't see a leak here, what are the cases when a leak might occur?

Jon Shemitz

unread,
Aug 31, 2011, 2:41:18 PM8/31/11
to android-...@googlegroups.com
By so carefully eliding the name of the class that contained the warning, you pretty much precluded the possibility of getting any sort of authoritative answer. But, presumably, the possible issue is precisely the opposite of your test case: an inner, private Handler that will stick around after the outer class instance that created the Handler has (supposedly) gone away. Since a non-static inner class instance has a reference to OuterClass.this, the outer class instance that created the Handler will be referred to as long as the Handler lives, and thus will not be garbage collected.

Ubuntu guy

unread,
Sep 1, 2011, 12:27:51 AM9/1/11
to android-platform
Hello,

There wasn't any intention to hide the class name. It was just a
test code.
I did notice that finalize method was invoked.

public class HelloAndroidActivity extends Activity {
Handler mh = new MyHandler();

class MyHandler extends Handler {
public MyHandler() {}


protected void finalize() {
Log.e(TAG,"handler finalized...");
}
}
...
...
...
Reply all
Reply to author
Forward
0 new messages