Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do lambdas in Android N jack compiler hold references to enclosing class?

Unlike anonymous inner classes, Java 8 lambdas don't hold references to the enclosing (parent) class. Android N adds support for lambdas.

However, they are implemented in the Jack compiler using anonymous inner classes for backward compatibility, as the note in the link states.

Does this mean that lambdas in Android classes compiled using Jack (and not retrolambda) will hold references to the enclosing class?

I know that one reason many people were excited about lambdas is to avoid Fragment or Activity leaks when using them, but at a cursory glance, it looks like using jack compiler will not give that benefit.

like image 950
Rohan Dhruva Avatar asked Mar 28 '16 21:03

Rohan Dhruva


1 Answers

I think the phrase "anonymous class" shouldn't be interpreted too literally here. In my understanding, the only thing they want to tell us is that Jack generates the classes at compile time (as opposed to the runtime approach of Java 8).

From the JackIrBuilder code I'd guess that the generated IR looks very similar to the bytecode that would be generated by retrolambda.

Jack seems to create a synthetic method containing the lambda body in the enclosing type and passes the reference of the enclosing instance to the generated class' constructor only in those cases where it is needed, i.e. when members of the enclosing instance are captured.

Reference: https://android.googlesource.com/toolchain/jack/+/0af676c4779c5b55fb321f491811516f3d74ed93/jack/src/com/android/jack/ir/impl/JackIrBuilder.java

So, from what I understand, the answer is: only when something needs to be captured from the enclosing instance.

like image 69
Stefan Zobel Avatar answered Sep 20 '22 23:09

Stefan Zobel