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

送分小仙女□ 提交于 2019-12-28 05:18:15

问题


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…



来源:https://stackoverflow.com/questions/28446626/do-java8-lambdas-maintain-a-reference-to-their-enclosing-instance-like-anonymous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!