我没有面临内存泄漏问题,但我需要知道内存泄漏是如何发生的。表格here下面的代码给出了内存泄漏。
private static Drawable sBackground;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);
setContentView(label);
}
有人能给我完整解释内存泄漏是如何发生的吗?以及GC如何无法收集引用?.
请解释一下下面的代码是否泄漏内存? ,如果是怎么回事?
private static Context context;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(context);
label.setText("Leaks are bad");
setContentView(label);
}
最佳答案
如果您拥有对象的引用
,GC
将如何运行。您必须先释放该对象。
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static references in other words you can say that an object becomes eligible for garbage collection if its all references are null.
请在此处阅读更多信息 How Garbage Collection works in Java
另请阅读本文,它将澄清您对 GarbageCollector
的疑虑
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
但在静态引用
的情况下,您仍然拥有该对象的引用,因此GC
不会在该对象上运行。
在此处了解更多信息 What is Automatic Garbage Collection?
关于java - Activity中的静态变量会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22626403/