This is a mirror of official site: http://jasper-net.blogspot.com/

Clearing up some confusion over finalization and other areas in GC

| Tuesday, November 16, 2010
In the WinDev conference that I just went to, there seems to be some confusion over finalization (such as why it even exists and etc) and other areas. I hope the following will clear up that confusion. If not, let me know.

Finalization

1)      Why we have finalization

Finalization is necessary because you want to make your component robust. You might have no control over your clients of your component in which case if you are seeing an issue (for example, opening a file handle in the exclusive mode before the finalizer closes it) you won’t be able to say “Oh, look this is a bug, go fix it” to whoever wrote the client (heck, the company that wrote the client might already went out of business!).

Obviously you want people to call Dispose on your object so the object doesn’t need to be promoted to a higher generation but you are not always in control of people calling Dispose, and very often you are not.

2)      What you can do in finalizers

Finalizers are only there so you can release your native resources. It’s by design not to do stuff with other managed objects because they would be taken care of by GC. Releasing native resources should be all you do in your objects’ finalize method and that’s a very important thing to do because we are not in a completely managed world – if that were the case, we wouldn’t need finalization at all.

3)      When the finalizer thread runs the finalizers

Each time we do a GC, we would see if there are any objects whose finalize method needs to run, if so we add it to the freachable queue and set an event to wait up the finalizer thread. Generally if a managed app is doing work, it will trigger GCs so this means whenever you trigger a GC, the finalizer thread, if it’s not already working, will immediately be aware that there are finalizers to run. The finalizer thread doesn’t wake up at “some random point of time in the future”. When it’s waken up is well defined.

So what if a finalizer takes a long time to run? Yes it would block the finalizers behind it from running. But remember we said you should only release native resources in your finalize method which should be fast. If it takes days to run a finalizer then there’s a problem in how you implemented the finalize method and you should look into that.

Read more: Maoni's WebLog

Posted via email from .NET Info

0 comments: