Do Java8 lambdas maintain a reference to their enclosing instance like anonymous classes?

前端 未结 2 416
一向
一向 2020-12-01 06:32

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 lamb

相关标签:
2条回答
  • 2020-12-01 06:54

    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…

    0 讨论(0)
  • 2020-12-01 07:08

    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.

    0 讨论(0)
提交回复
热议问题