简体   繁体   中英

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.

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.

Please help to examine whether I am understanding memory leakage in Java correctly, thanks in advance!

In the first example, v still holds references to the 100 objects. 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.
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.
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.

The references to the 100 object do not remain . '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). 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.

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. You don't have to set it to null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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