Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of the object created in infinite loop

I have a very basic question.

I write a loop like this:

while(true)
{
   MyTestClass myObject = new MyTestClass();
}
  1. When will be the object created in the loop, garbage collected?
  2. Also, for every iteration, is it that the new memory location is allocated to the myObject reference?
  3. What if i write myObject = null; at the end of every iteration?
like image 919
Amey Avatar asked Jul 08 '10 09:07

Amey


People also ask

Which method is called by garbage collection?

The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM. Object class finalize() method has an empty implementation.

What is the garbage collection in the content of?

Concept: Java garbage collection is the process of releasing unused memory. Sometimes some objects are no longer required by the program and when there is no reference to an object, then that object should be released. This process is known as garbage collection.

What are the phases of garbage collection?

Garbage collection then goes through the three phases: mark, sweep, and, if required, compaction.

What is garbage collection system?

Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.


1 Answers

  1. whenever GC feels like it, frankly; the variable is never read, so it is always eligible
  2. myObject is the variable - that has a fixed position on the stack for the reference; however, each new MyTestClass() is a different object, created somewhere in the available heap space; different each time
  3. no difference whatsoever; strictly speaking there are some complexities involving the actual declaration point of the variable (in IL) and how while is actually implemented - but that would only show after exiting the loop. And since on each iteration you immediately allocate it, there is no tangible difference here
like image 143
Marc Gravell Avatar answered Nov 15 '22 23:11

Marc Gravell