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

问题描述

匿名类维护对其封闭实例的引用,这可能导致Android上下文泄漏。

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

由于将lambdas向后移植到Java7,因此值得一试。

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


这对内存管理有一个有益的含义:内在类实例总是保持对其封闭实例的强引用,不从封闭实例捕获成员的lambda不保存对它的引用。内部类实例的这种特性通常可能是内存泄漏的来源(所谓的失效监听器问题)

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 lambdas是否像匿名类一样维护对其封闭实例的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:09