Reputation: 19102
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
Upvotes: 1
Views: 149
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 reachablesomeObject
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
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
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