[英]Why does simple example using Activity in Android cause a memory leak?
I got the following example and Im not sure why this is causing a memory leak?我得到了以下示例,但我不确定为什么会导致内存泄漏? I can not wrap my head around it?!
我不能绕着它转吗?!
public class MyLeakActivity extends Activity {
// static reference to evil
private static final Evil e;
public MyLeakActivity() {
e = new Evil();
}
private final class Evil {
}
}
Thanks in advance.提前致谢。
greetings Fabian问候法比安
Take a look here ... this article is geared toward Android development.看看这里……这篇文章是针对 Android 开发的。
https://dzone.com/articles/a-troublesome-legacy-memory-leaks-in-java https://dzone.com/articles/a-troublesome-legacy-memory-leaks-in-java
I think your design might never allow the enclosing class to be gc'd.我认为您的设计可能永远不会允许封闭类被 gc'd。 Unless you have a very good reason to use a non-static inner class (maybe for scope reasons,) a good rule of thumb is to always begin with the inner class declared as static.
除非您有充分的理由使用非静态内部类(可能出于范围原因),否则一个好的经验法则是始终从声明为静态的内部类开始。
在创建新对象之前,您应该检查 e == null 是否。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.