Does an instance of an anonymous inner class store all the accesible final variables or does it store only the variables that are being used inside the said inner class? (i.e. does it perform some kind of analysis? As far as I know the reference to the parent instance is being stored no matter what.)
Asked
Active
Viewed 202 times
3
-
I believe this thread can be helpful:http://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class – Konstantin Yovkov Oct 23 '14 at 08:08
-
Re-opened because the linked thread does not answer the question how many of these final variables are copied. – Thilo Oct 23 '14 at 08:17
1 Answers
1
The reference to the enclosing class is stored no matter what.
Final variables are stored as a copy, but only if you actually reference them somewhere in your inner class. This does not really required any extra "analysis" but can be done in the normal compile step (the compiler has to resolve the variable anyway, so it can output the code to set up the copy, too).

Thilo
- 257,207
- 101
- 511
- 656
-
Okay, I am just stating this without any reference. Maybe someone can fill in a bytecode dump for a minimal compiled class to demonstrate. – Thilo Oct 23 '14 at 08:12
-
Here is one such dump, but it does not answer the part about variables that are not needed: http://stackoverflow.com/a/2804940/14955 – Thilo Oct 23 '14 at 08:16
-
3It is very probable that a compiler which stored all the local vars would still be compliant with the specification. In other words, the behavior being discussed is implementation-dependent in principle. In practice, you are 100% right as no sane compiler would actually go out of its way to store more than necessary. – Marko Topolnik Oct 23 '14 at 08:24
-
One would hope so. Especially since it is common good practice to make every variable and parameter final unless it has to be modified, and that would add a nasty hidden overhead here. – Thilo Oct 23 '14 at 08:31
-
1Notice additionally that with Java 8 the captured variable does not need to be final at all. So the local class could potentially capture all *effectively final* variables. – Marko Topolnik Oct 23 '14 at 08:33