Wednesday, April 29, 2009

Finalizers and Thread local storage

Sunset from our balcony

Writing finalizers is generally tricky. In the msdn documentation for finalizers the following limitations are mentioned.

  1. The exact time when the finalizer executes during garbage collection is undefined
  2. The finalizers of two objects are not guaranteed to run in any specific order
  3. The thread on which the finalizer is run is unspecified.
  4. Finalizers might not be run at all

#3 has interesting consequences. If a native resources is allocated by a managed ctor (or any other method) and the finalizers is used to de-allocate that then the allocation and de-allocation will not happen on the same thread. The reason being that the CLR uses one (maybe more than one) special thread to run all finalizers on. This is easily verified by the fact that if you query for the thread id inside the finalizers you will get a different id than the main thread the application is being run on.

The thread safety is generally easy to handle but might lead to some tricky and hard to locate problems. Consider the following code

class MyClass
{
public MyClass()
{
tls = 42;
Console.WriteLine("Ctor threadid = {0} TLS={1}", AppDomain.GetCurrentThreadId(), tls);
}

~MyClass()
{
Console.WriteLine("Finalizer threadid = {0} TLS={1}", AppDomain.GetCurrentThreadId(), tls);
}

public void DoWork()
{
Console.WriteLine("DoWork threadid = {0} TLS={1}", AppDomain.GetCurrentThreadId(), tls);
}

[ThreadStatic]
static int tls;
}

class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.DoWork();
mc = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

Here we create a class, use it and finalize it. In all of these 3 methods we print the thread id and also use a special variable named tls.


If you see the tls is marked with the attribute ThreadStatic. The definition of ThreadStatic is “Indicates that the value of a static field is unique for each thread”.


I hope by now you have figured out the gotcha :). Under the hood the CLR uses a native OS concept called Thread Local Usage (TLS) to ensure that the value of tls is unique per thread. TLS uses special per thread data-structure to store that data. Now we have set the value in the ctor and used it in finalizer. Since they run on different threads each will get different values of the same field.


On my system the out put is as follows

Ctor threadid = 5904 TLS=42
DoWork threadid = 5904 TLS=42
Finalizer threadid = 4220 TLS=0
Press any key to continue . . .

As is evident the finalizer ran on a different thread (id is different) and the TLS value is also different from what was set.


So the moral of this story is “Be careful about thread safety of finalizers and do not use thread local storage in it

17 comments:

Anonymous said...

Just to share an expirience:
I found a solution to grab Youtube movies. Some of are webs where you put the url from YouTube and it gives you file with strange extension and small size. Some are really complicated.
My way was to use moviesherlock (moviesherlock.com or sm like this - please ask me - will rememeber). Really simple utility, that just works, and only 1 button in software.
[url=http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde]I downloaded it from here: http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde[/url].
I downloaded even HD movies!

But it looks too easy, has no player, but just works. It downloaded ~12 concurrent movies for me and actually slows down my system. Its possible to do search in [url=http://moviesherlock.com]moviesherlock[/url] and search results differs from what you see in YouTube. Thats strange.
Who knows - youtube results are different for same text? I likes cat (Simons cat / dog).
Why doesn't youtube allows to download its movies without external tools?!! It actually sucks!

Thanks in advance!

Anonymous said...

Just to share an expirience:
I found a solution to rip YouTube movies. Some of are webs where you put the url from YouTube and it gives you file with strange extension and small size. Some are really complicated.
My way was to use moviesherlock (moviesherlock.com or sm like this - please ask me - will rememeber). Really simple utility, that just works, and only 1 button in software.
[url=http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde]I downloaded it from here: http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde[/url].
I downloaded even HD movies!

But it looks too easy, has no player, but just works. It downloaded ~12 concurrent movies for me and actually slows down my system. Its possible to do search in [url=http://moviesherlock.com]moviesherlock[/url] and search results differs from what you see in YouTube. Thats strange.
Who knows - youTube search are same for same text? I loves cat (Simons cat / dog).
Why doesn't youtube allows to download its movies without external tools?!! It actually sucks!

Thanks in advance!

Anonymous said...

Just to share an expirience:
I digg a solution to rip Youtube videos. Some of are sites where you put a link from YouTube and it gives you file with strange extension and small size. Some are really complicated.
My way was to use moviesherlock (moviesherlock.com or sm like this - please ask me - will rememeber). Really simple utility, that just works, and only 1 button in software.
[url=http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde]I downloaded it from here: http://download.cnet.com/3001-2140_4-75065920.html?spi=68a87b0bad1ea20e12285c5005469cde[/url].
I downloaded even HD movies!

But it looks too simple, has no player, but just works. It downloaded ~12 concurrent movies for me and actually slows down my system. Its possible to do search in [url=http://moviesherlock.com]moviesherlock[/url] and search results differs from what you see in YouTube. Thats strange.
Who knows - youtube search are same for same text? I likes cat (Simons cat / dog).
Why doesn't youtube allows to download its movies without external tools?!! It actually sucks!

Thanks in advance!

Anonymous said...

Howdy,
I'm Looking to buy [url=http://www.milesgershon.com/entertainment-centers.html][b]Entertainment Centers[/b][/url] or [url=http://www.milesgershon.com][b]Wall Units[/b][/url] For a new hotel chain I'm working at in.
Can you guys give me a good recommendation of where is the leading deal on these? I live in New York and I heard that the main thing about these [url=http://ent3rtacn3tr.webnode.com/?aw=1][b]Entertainment Centers[/b][/url] is the cost of shipping and installation.
Thanks

Rex

Anonymous said...

Guys,

I need some advice
I'm Looking to buy [url=http://www.milesgershon.com/tv-stands.html][b]TV Stands[/b][/url] or a TV [url=http://www.milesgershon.com][b]Wall Unit[/b][/url] For a loft I'min the process of buying.
Can you guysgive me a good recommendation of where is the bestplace to buy these? I live in New York and I heard that the big thing about these [url=http://www.milesgershon.com][b]tv stands[/b][/url] is the cost of shipping and installation.


much appreciated

Mike Millican

Anonymous said...

Does anyone know of an exactly how various countries are ration seeing that Haiti and what countries they are?
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=14220"]car acoustics[/url] car audio, acoustics system
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=14245"]buy lighters[/url] zippo lighters, bic products
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18099"]shaadi[/url] muslim shaadi, mujhse shaadi karogi
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18100"]mother of the bride dresses[/url] plus size discounted mother of the bride dresses, mother of the bride dresses with sleeves
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18095"]pyramat[/url] pyramat g-flex sound booster portable audio chair, pyramat gaming chair
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18096"]sherpani[/url] sherpani luna backpack, sherpani bag
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18097"]STOKKE HIGH CHAIR[/url] stokke tripp trapp high chair, tripp trapp
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18098"]Tolomeo desk lamps[/url] api executive desk lamps, api antique executive desk lamps
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18101"]DOUBLE GLAZING WINDOW HANDLES[/url] how to install double glazing windows, double glazing window hinges
[url="http://avida-ed.msu.edu/cgi-bin/mwf/topic_show.pl?tid=18102"]tuff shed[/url] tuff sheds cheap, tuff shed barn deluxe

I mean services like sites on high... Who can serve?
Thanks

Anonymous said...

[url=http://www.vo2ov.com/]Porn Download[/url]
[url=http://www.vo2ov.com/]GCD[/url]
[url=http://www.vo2ov.com/]gongchandang[/url]
[url=http://www.vo2ov.com/]lihongzhi[/url]

Anonymous said...

Hello swantosad levitra cost In this way, Levitra initiates natural response process of sexual stimulation. [url=http://www.mynorthcanton.com/]buy generic levitra[/url] - Initially the patient is prescribed to take a dose of 10 mg 25 to 60 minutes before having sex. http://www.mynorthcanton.com/ - buy cheap levitra Ideally the highest quantity should not exceed 20 mg and the lowest quantity should be 5 mg per day.

Anonymous said...

Want to share my own experience, hope it helps somebody.
Ihave an iTunes account user and there are gigabites of m4p files on my hard drive. Of course I used to listen to them on iPod. But last month my iPod was stolen (sh*t!) and I've got a new mp3 player on my birthday! Obviously I was unable to transfer my M4P collection to it because these file had iTunes DRM protection. Luckily I found [url=http://mp4-converter.info]M4P converter[/url] and converted all my iTunes library just in few clicks!So I recommend this [url=www.mp4-converter.info]M4P converter[/url] if you have any problems with protected files - it can convert them to unprotected MP3 or any other format so you can play them without iTunes application.
The url is mp4-converter.info or something like this. Tell me if you need exact will go thru my mail

Anonymous said...

Sharing my own story, hope it helps someone.
I'm an iTunes subscriber and there are gigabites of itunes files on my machine. Of course I listened to them on iPod. But last month my iPod was broken (sh*t!) and I've got a new zune player on St Valentine's day! Obviously I was unable to transfer my M4P collection to it because these file had iTunes DRM protection. Fornately I found [url=http://mp4-converter.info]M4P converter[/url] and converted all my iTunes library just in few clicks!So I recommend this [url=www.mp4-converter.info]M4P converter[/url] if you have any problems with protected files - it will convert them to unprotected MP3 or any other format so you can use them on any player or PC.
The url is mp4-converter.info or something like this. Tell me if you need exact will go thru my mail

Anonymous said...

Sharing my story, hope it helps someone.
I'm an iTunes subscriber and there are gigabites of iTunes M4P files on my PC. Of course I listened to them on iPod. But last month my iPod was stolen (sh*t!) and I've got a new mp3 player on St Valentine's day! Obviously I couldn't transfer my M4P collection to it because these file had iTunes DRM protection. Fornately I found [url=http://mp4-converter.info]M4P converter[/url] and converted all my iTunes files just in few clicks!So I would recommend this [url=www.mp4-converter.info]M4P converter[/url] if you have any problems with protected files - it can convert them to unprotected MP3 or any other format so you can play them without iTunes application.
The url is mp4-converter.info or something like this. Tell me if you need exact will go thru my mail

Anonymous said...

Sharing my story, hope it helps someone.
Ihave an iTunes account subscriber and there are gigabites of iTunes M4P files on my hard drive. Of course I used to listen to them on iPod. But recentluy my iPod was stolen (sh*t!) and I've got a new zune player on my birthday! Obviously I couldn't transfer my M4P collection to it because these file had iTunes DRM protection. Luckily I found [url=http://mp4-converter.info]M4P converter[/url] and converted all my iTunes library just in few clicks!So I would recommend this [url=www.mp4-converter.info]M4P converter[/url] if you have any problems with protected files - it can convert them to unprotected MP3 or any other format so you can use them without iTunes application.
The url is mp4-converter.info or something like this. Tell me if you need exact will go thru my mail

Anonymous said...

http://markonzo.edu Very funny pictures actual ashley furniture [url=http://jguru.com/guru/viewbio.jsp?EID=1536072]actual ashley furniture[/url], :-1, watch allegiant air [url=http://jguru.com/guru/viewbio.jsp?EID=1536075]watch allegiant air[/url], ojbditg, best pressure washers [url=http://jguru.com/guru/viewbio.jsp?EID=1536078]best pressure washers[/url], orcydlo, follow dishnetwork [url=http://jguru.com/guru/viewbio.jsp?EID=1536080]follow dishnetwork[/url], jmroo, fresh adt security [url=http://jguru.com/guru/viewbio.jsp?EID=1536076]fresh adt security[/url], osydy,

Anonymous said...

On a recent Saturday night, my wife and I visited Town Center in West Des Moines, Iowa and browsed through several of the stores.

Since it had been years since I had visited a [URL=http://boycottspencergifts.org/]teen[/URL] store, I walked into the store and was completely surprised, appalled, and disgusted with the merchandise available. I knew they carried adult items and novelty gifts, but I had no idea the selection was so varied, so explicit, so offensive, and so readily available to anyone who entered the store.

Both my wife and I are in our 40's, don't consider ourselves "prudes" or overly conservative, and believe we have a strong sense of what is appropriate for our two teenage children.

Neither one of us could believe what was on display and available to any age shopper merely feet from the door at this one. I was sickened thinking our children, as well as every child who visits Town Center, have access to the store and the items on display.

We truly believe this type of merchandise should be limited to adult oriented stores that have strict age requirements and are closely monitored and regulated.

If you must, visit the store yourself and observe the items for sale.Please consider taking measures to help eliminate the adult items, products which promote drug usage, and the other offensive merchandise from this business.

They may be offering these items for sale and staying within the lette of the law, but responsible citizens need to take a stand, change the laws, and reduce or completely eliminate the availability of these items at public and family places such as Town Center.

http://www.boycottspencergifts.org

Anonymous said...

I think, that you are not right. Let's discuss. Write to me in PM.

Anonymous said...

Hey,

When ever I surf on web I never forget to visit this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]geekgyan.blogspot.com really contains lot of useful information. Frankly speaking we really do not pay attention towards our health. Let me present you with one fact here. Recent Research displays that nearly 70% of all United States grownups are either fat or weighty[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Hence if you're one of these people, you're not alone. In fact, most of us need to lose a few pounds once in a while to get sexy and perfect six pack abs. Now next question is how you can achive quick weight loss? [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss[/url] is not like piece of cake. You need to improve some of you daily habbits to achive weight loss in short span of time.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health trainer who can help you lose weight quickly. If you do not want to go under difficult training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effective weight loss.

Anonymous said...

VIMUTO!

http://www.vimuto.com

Is a free web [url=http://www.vimuto.com/]proxy[/url] service that [url=http://www.vimuto.com/]unblock[/url] popular sites like facebook.com, myspace.com, youtube.com and many more! Unblock these at work, school, library, or anywhere else! This website is not just to unblock buck to surf anonymously and keep your identity!

You can surf through many different locations with speeds you have not seen on other proxies before!

Our script and theme is fully custom for greatest speeds and has a pleasing look to the eye and is an amazing [url=http://www.vimuto.com/]IP Hider[/url].

We also have a live 24/7 radio you may listen to while you surf!

This website is 100% free and FREE of any ads!

Check us out! You won't be disappointed!