简体   繁体   English

我在Java中正确理解内存泄漏吗

[英]Am I understanding Memory Leakage correctly in Java

For this code fragment: 对于此代码片段:

Vector v = new Vector(10);
  for (int i = 1; i<100; i++)
     {Object o = new Object();
      v.add(o);
      o = null;
     }

There won't be leakage since all the references to the 100 objects have been set to null, thus they will be collected by GC. 因为对100个对象的所有引用都设置为null,所以不会泄漏,因此它们将由GC收集。

However, 然而,

 Vector v = new Vector(10);
  for (int i = 1; i<100; i++)
     {Object o = new Object();
      v.add(o);
      }
   v= null;

There will be leakage, since I only nulled the reference to the vector, but all the references to the 100 objects still remain, thus won't be GC collected while they are of no use to the system. 因为我仅使对向量的引用为空,但仍保留了对100个对象的所有引用,所以会发生泄漏,因此在它们对系统无用时将不会收集GC。

Please help to examine whether I am understanding memory leakage in Java correctly, thanks in advance! 请帮助检查我是否正确理解了Java中的内存泄漏,在此先感谢您!

In the first example, v still holds references to the 100 objects. 在第一个示例中, v仍然保留对100个对象的引用。 When v will get out of scope, it will be a candidate to garbage collection, when it is collected all the 100 objects can be collected as well. v超出范围时,它将是垃圾回收的候选对象,当v被回收时,所有100个对象也可以被回收。
In the second example - when you set v to null, it will be a candidate to garbage collection, when it is collected all the 100 objects can be collected as well. 在第二个示例中-将v设置为null时,它将是垃圾收集的候选对象,当收集到它时,也可以收集所有100个对象。
So, in both cases there shouldn't be any leakage. 因此,在两种情况下都不应有任何泄漏。

Generally, there is no real need in setting a local variable to null, when the method ends, it will get out of scope and will be subject for GC. 通常,没有真正的必要将局部变量设置为null,方法结束时,它将超出范围并受GC约束。

The references to the 100 object do not remain . 对100对象的引用不会保留 'o' obviously goes out of scope at each iteration of the for loop, leaving only the reference internal to the vector (the o=null in your first case is pointless). 'o'显然在for循环的每次迭代时都超出范围,仅在向量内部保留引用(在第一种情况下, o=null是毫无意义的)。 When you set v to something else (null), there are no more reference to the vector, so it and its contents can be garbage collected. v设置为其他值(空)时,将不再引用该向量,因此可以对其进行垃圾回收。

That's what "reference counting" is about; 这就是“引用计数”的含义; it's the number of valid references remaining. 这是剩余的有效引用数。 You cannot loose them the way you can loose a pointer in C. If the scope of a reference is gone (eg, because it is local to a function), the reference is gone. 您无法像使用C中的指针那样松开它们 。如果引用的范围已消失(例如,因为它在函数中是局部的),则引用已消失。 You don't have to set it to null. 您不必将其设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM