Do Java8 lambdas maintain a reference to their enc

2019-01-13 17:53发布

问题:

We know that anonymous classes maintain a reference to their enclosing instance and that this can lead to context leaks on Android.

Since retrolambda backports lambdas to Java7, it could be worth a try.

It seems that Java8 lambdas do not have this problem, but I can't find any official information on that.

Any clue?

回答1:

Here is some info.

From the following link http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html: This has a beneficial implication for memory management: while inner class instances always hold a strong reference to their enclosing instance, lambdas that do not capture members from the enclosing instance do not hold a reference to it. This characteristic of inner class instances can often be a source of memory leaks (the so-called lapsed listener problem)

You can also see http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html from the text: Nested class: Use it if your requirements are similar to those of a local class, you want to make the type more widely available, and you don't require access to local variables or method parameters.

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.



回答2:

Lambda expressions and method references capture a reference to this only if required, i.e. when this is referenced directly or an instance (non-static) member is accessed.

Of course, if your lambda expression captures the value of a local variable and that value contains a reference to this it implies referencing this as well…