Does an anonymous class live?

Take a look at the following link: GLSurfaceView Code Example

In particular, look at the following function in the second code block on this 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 bothers me is that anon Runnable refers to a very local event object, but queueEvent actually finishes running Runnable on a completely separate thread, and possibly long after this particular instance of the event is long dead. which is obviously a problem. Or is it that, like using local-ref-in-anon-class, it actually does +1 in the ref-count of the event object, so that it gets stuck as long as anon Runnable is still breathing?

Also, does the fact that MotionEven is declared final have anything to do with all this?

PS As a related question (although this is not my main problem), what if instead of (or in addition to) "event" we wanted to call some kind of primitive, such as "int x" inside the anon class, what happens then? (seeing that you can’t +1 the number of primitive links).

+4
source share
3 answers

Java does not use reference counting to collect garbage. I am not very good at how the JVM implements such a closure, but I can only assume that the instance of the anonymous class contains a reference to event . In this case, while the anonymous Runnable is alive, then everything that it refers to is alive (and all links to these things are alive, etc. Etc.).

As for primitive types, they are simply copied directly to the fields. Thus, there are no "references" to what should live as long as it refers, and then collect garbage; they are just part of the objects that contain them. Each time you β€œmake a new link” to int 287, this does not mean that there is a storage location 287, to which you now have another link, you just have a different storage word that stores 287. Thus, it does not matter when 287 you originally received from you is freed, yours is completely independent.

+3
source

Yes, Runnable contains a link to MotionEvent . MotionEvent cannot collect garbage until the Runnable is collected.

Inside the inner class, only local variables of final can be referenced.

By the way, do not assume that reference counting is used; most garbage collectors do not currently use reference counting.

+4
source

You can only refer to a variable if it is declared final, and the stream will contain a link to it, which prevents it from collecting garbage.

+2
source

All Articles