views:

136

answers:

4

Let's say i'm trying to allocate 100 bytes, but since I don't have 100 bytes available in my GC heap, a garbage collection is triggered. Also, in my GC heap there's 100mb worth of unreachable objects. To my understanding, once the GC freed 100bytes, he could decide to stop the collection and continue the program's execution. So let's say the GC didn't freed 50mb worth of objects, that are equal to 100 different objects.

My question is this: does the GC invoke all of the finalizers? even though it isn't going to delete them? (in this case, the 100 unreachable objects that the GC decided not to delete).

+11  A: 

The problem is that anything here could be an implementation detail, and it could be different between x86 / x64 / ia64, server vs workstation (very different GC profile), Mono vs MS .NET, OS version, .NET/CLI major version, .NET/CLI patch version, Compact Framework, Micro Framework, etc.

I don't think you should assume any specific behaviour, other than "objects with finalizers that are not in use will probably get finalized at some point, but even that isn't guaranteed".

Marc Gravell
+1. And yes, in other words, "you can't know and shouldn't really think about it".
Adam Robinson
I.e., "Whereof one cannot speak, thereof one must be silent."
mlo
A: 

The answer is no. The only time the finalizers are run is when the object is being destroyed.

Gabriel McAdams
"Are finalizers called even though [an object] has not been garbage collected?" - Clearly: no
Alex
A: 

The GC does multiple passes. It looks for unreachable objects and when it finds them checks if they have a finalizer. If there is a finalizer, then it puts them into a separate finalizer queue and if not, cleans them up. So on first pass, it doesn't actually call any finalizers, it just organizes objects based on whether or not they have finalizers.

Sam
You've missed the point of my answer ... the question is whether the GC can decide to stop a collection once it dosen't need to free any more objects (so their finalizer won't be invoked even though "some collection" happened)
+1  A: 

"once the GC freed 100bytes, he could decide to stop the collection" - no, the GC wouldn't stop collection. It will always collect generation 0. If that's not sufficient, go on with Gen1 and Gen2+LOB.

Alex