Gaurav Agarwal
Gaurav Agarwal

Reputation: 19102

When will Objects added to a Collection in a loop be Garbage Collected?

In the following code

List<SomeObject> someObjectList = new ArrayList<SomeObject>();

do {

    SomeObject someObject = new SomeObject();

    someObjectList.add(someObject);

} while(some condition is met);

My Question

  1. When will someObject be grabage collected?
  2. Am I leaking memory here?

Upvotes: 1

Views: 149

Answers (3)

kosa
kosa

Reputation: 66637

When will someObject be grabage collected?

someObject will be GCed when it is no longer reachable. In the simple example provided, this could happen when either of the following occur:

  • someObjectList is no longer reachable
  • someObject is removed from someObjectList (thus making it no longer reachable)

Am I leaking memory here?

As far as I know there is nothing points to memory leak in your code.

Upvotes: 4

Andreas Dolk
Andreas Dolk

Reputation: 114767

someObject is a local variable and that will never be garbage collected. This someObject is "something" on the stack or in a register. Local variables itselves are not java objects.

someObject temporarily holds a reference to an instance of SomeObject. And that reference is stored in the array inside the array list.

This instance of SomeObject will be garbage collected some time after no other object holds a reference to that instance.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200148

someObject will not be GC'd until your loop exits. Whether this is a memory leak or not is open to interpretation. If you expect it to be freed while still iterating, then you are leaking. If not, then you're not.

Upvotes: 2

Related Questions