Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Java's garbage collector go ahead and take care of variables declared within loops?

If I have:

for (int i; i != 100; i++) {
    ArrayList<String> myList = buildList();
    //... more work here
}

Do I have to set myList to null at the end of my loop to get the GC to reclaim the memory it uses for myList?

like image 536
slim Avatar asked Oct 18 '10 15:10

slim


People also ask

How does Java's garbage collector work?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

What is the role of a garbage collector in a running program?

In the common language runtime (CLR), the garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory for an application. Therefore, developers working with managed code don't have to write code to perform memory management tasks.

How does garbage collection work when it will be triggered?

When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.

Does garbage collector handle cyclic references?

yes Java Garbage collector handles circular-reference! How? There are special objects called called garbage-collection roots (GC roots). These are always reachable and so is any object that has them at its own root.


2 Answers

The GC will automatically clean up any variables that are no longer in scope.

A variable declared within a block, such as a for loop, will only be in scope within that block. Once the code has exited the block, the GC will remove it. This happens as soon as an iteration of the loop ends, so the list becomes eligible for garbage collection as soon as each iteration of the loop finishes.

The scope of a variable is also why i would not be valid after your example loop.

Note that this only is the case if you use the variable only within the loop. If you pass it to another method that keeps a reference to it, your variable will not be garbage collected.

like image 81
Alan Geleynse Avatar answered Nov 15 '22 22:11

Alan Geleynse


Lord, no! Java's GC is much, much, much smarter than that.

like image 43
Matt Ball Avatar answered Nov 15 '22 20:11

Matt Ball