Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a garbage collector avoid an infinite loop here?

Consider the following C# program, I submitted it on codegolf as an answer to create a loop without looping:

class P{     static int x=0;     ~P(){         System.Console.WriteLine(++x);         new P();     }     static void Main(){         new P();     } } 

This program looks like an infinite loop in my inspection, but it seems to run for several thousand iterations, and then the program terminates successfully without error (No errors are thrown). Is it a spec violation that the finalizer for P eventually is not called?

Clearly this is stupid code, that should never appear, but I am curious as to how the program could ever complete.

Original code golf post:: https://codegolf.stackexchange.com/questions/33196/loop-without-looping/33218#33218

like image 481
Michael B Avatar asked Jul 09 '14 19:07

Michael B


People also ask

How does an infinite loop stop?

An infinite loop can stop because of the memory if the memory grows in the loop. In this case, there is no memory grow. But, if you create some new heavy objects in every iteration of the loop, then it will stop eventually due to a Memory Limit Exception.

How do you make sure that the garbage collector is done running when you call?

System. GC. Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.


2 Answers

As per Richter in the second edition of CLR via C# (yes I need to update):

Page 478

For (The CLR is shutting down) each Finalize method is given approximately two seconds to return. If a Finalize method doesn't return within two seconds, the CLR just kills the process - no more Finalize methods are called. Also, if it takes more then 40 seconds to call all objects' Finalize methods, again, the CLR just kills the process.

Also, as Servy mentions, it has its own thread.

like image 50
Eric Scherrer Avatar answered Sep 23 '22 02:09

Eric Scherrer


The finalizer doesn't run in the main thread. The finalizer has its own thread that runs code, and it's not a foreground thread that would keep the application running. The main thread completes effectively right away, at which point the finalizer thread simply runs as many times as it gets a chance to before the process gets torn down. Nothing is keeping the program alive.

like image 27
Servy Avatar answered Sep 26 '22 02:09

Servy