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

前端 未结 2 425
一向
一向 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 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.

提交回复
热议问题