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).
Java doesn’t use reference counting to do its garbage collection. I don’t know a lot specifically about how the JVM implements this sort of closure, but I can only presume the anonymous class instance contains a reference to
event. That being the case, as long as the anonymous Runnable is alive then everything it references is alive (and everything those things reference is alive, etc, etc).As for primitive types, they’re just copied directly into the fields. So there are no ‘references’ to something that needs to live as long as it is referenced and then be garbage collected; they’re just a part of the objects that contain them. Every time you “make a new reference” to the int 287, it’s not that there is a place storing 287 to which you now have another reference, you just have another memory word storing 287. So it doesn’t matter when the 287 you originally got yours from is deallocated, yours is completely independent.