本文介绍了Java8 lambda 是否像匿名类一样维护对其封闭实例的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道 匿名类维护对其封闭实例的引用,这可能会导致 Android 上的上下文泄漏.

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

由于 retrolambda 将 lambda 反向移植到 Java7,因此值得一试.

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

看来 Java8 lambdas 没有这个问题,但我可以't 找到任何官方信息.

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

有什么线索吗?

推荐答案

这里有一些信息.

来自以下链接 http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html:这对内存管理有一个有益的影响:虽然内部类实例总是持有对其封闭实例的强引用,但不从封闭实例中捕获成员的 lambda 不持有对它的引用.内部类实例的这种特性往往会成为内存泄漏的源头(所谓的lapsed listener问题)

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)

您还可以查看http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html来自正文:嵌套类:如果您的需求与本地类相似,您希望该类型更广泛地可用,并且您不需要访问本地变量或方法参数,请使用它.

You can also see http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.htmlfrom 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.

这篇关于Java8 lambda 是否像匿名类一样维护对其封闭实例的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:09