java - Activity中的静态变量会导致内存泄漏吗?

标签 java android memory memory-leaks

我没有面临内存泄漏问题,但我需要知道内存泄漏是如何发生的。表格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/

相关文章:

java - 由 : java. lang.NullPointerException 引起:尝试调用虚拟方法 'java.lang.String com.facebook.Profile.getFirstName()'

c - 分配过多内存的性能损失(?)

c# - 你能给我一个在 .NET 中导致内存碎片的例子吗

java - 递归生成ASCII二叉树

java - 无法通过 Dispatcher 访问 AEM/etc.clientlibs

java - 当我的应用程序运行时,硬件音量按钮不起作用

java - 谷歌地图 : Multiple values in snippet

java.io.IOException : wrong key class: X is not class <ReducerOutputClass>

java - 如何将用户当前用户详细信息插入 Firebase 中的另一个节点?

JavaScript 原语 : same memory location, 新的内存位置,还是依赖于引擎?