-1

For the below codes, after the for loop, will memory leak still happen please?

static List list = new ArrayList();
for (int i = 1; i<100; i++){
  Object o = new Object();
  v.add(o);
  o = null;
}
Sam003
  • 540
  • 6
  • 17
  • "will memory leak still happen" - why do you think you have a memory leak in the first place? – John3136 Jul 22 '15 at 03:37
  • Thanks @John3136 When the garbage collector track all the references in the stack, and will find all the o objects are still be referenced by list even when there is no more reference to list. In this case, all the o objects will not be garbage-collected. – Sam003 Jul 22 '15 at 03:44
  • Yeah, and then the list goes out of scope, and it and all its elements get collected. – chrylis -cautiouslyoptimistic- Jul 22 '15 at 03:53
  • 1
    possible duplicate of [Which loop has better performance? Why?](http://stackoverflow.com/questions/110083/which-loop-has-better-performance-why) – duplode Jul 22 '15 at 03:58
  • They won't be garbage collected, because you put them in the list. If you put them in the list, that's because you want them in the list. If you want them in the list, then you don't want them to be garbage collected. Where does a "memory leak" come into the picture here? If you don't want them in the list, then putting them in the list will do things that you don't want. But you don't need to think about "memory leaks" to understand that. – Dan Getz Jul 22 '15 at 04:28

1 Answers1

0

Fear not, the garbage collector will collect the garbage. Yes, every time o = null; creates garbage as the reference lost but GC collects it. Always try to avoid creating objects into any loops.

I think giving Yes/No answer will help you less whereas you will be more beneficial if you know when true memory leaks occur in java. So read Creating a memory leak with Java

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • I read a article, and was kinda convinced that memory leak could still happen here even every time I set o = object. When the garbage collector track all the references in the stack, and will find all the o objects are still be referenced by list even when there is no more reference to list. In this case, all the o objects will not be garbage-collected. – Sam003 Jul 22 '15 at 03:43
  • Thanks. I think I got it. – Sam003 Jul 22 '15 at 15:53