Have peek at the following link: GLSurfaceView code sample
Specifically, look at the following function in the second code block on that page:
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {
public void run() {
mRenderer.setColor(event.getX() / getWidth(), event.getY() / getHeight(), 1.0f);
}
});
return true;
}
What confuses me here is that the anon Runnable references the very much local "event" object, but queueEvent actually ends up running the Runnable on a completely separate thread, and thus possibly long after that particular instance of "event" is long dead, which is obviously a problem. Or is it the case that sort of of local-ref-within-anon-class usage actually does a +1 on the ref count of the "event" object so that it sticks around as long as the anon Runnable is still breathing?
Also, does the fact that the MotionEven is declared final have anything to do with all of this?
P.S. As a related question (though it's not my main concern), what if instead of (or in addition to) "event" we wanted referenced some primitive like "int x" inside of the anon class, what happens then? (seeing as you can't +1 the ref count of a primitive).
Yes, the Runnable
keeps a reference to the MotionEvent
. The MotionEvent
cannot be garbage collected until the Runnable
is collectible.
Only final
local variables can be referenced from within an inner class.
By the way, don't assume reference counting is used; most garbage collectors don't use reference counting nowadays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With