Day of the Developer

Living the life of a developer. What is development work really like?

<October 2006>
SuMoTuWeThFrSa
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

Post Categories

Article Categories

News

I'm a dad :) Welcome to a new life.

Navigation

Software Business Tips

My Sites

Subscriptions



A Gotcha with Thread Static variables

I normally use static variable declarations like so:

private static ArrayList m_Cards = new ArrayList();

With some code I was working on I recently had to switch to using Thread Static variables

[ThreadStatic()]
private static ArrayList m_Cards = new ArrayList();

And suddenly found that the SECOND or later time the object was referenced, it threw a NullReferenceException

Turns out that while the declaration is Thread Static, the initialisation is still static.

So the first call triggers the initialisation.  Later calls may use the same thread (safe) or another thread (not initialised).

The end result is that you have to switch to using lazy initialisation.

I usually do that like this:

[ThreadStatic()]
private static ArrayList m_Cards = new ArrayList();
public ArrayList Cards {
    get {
        if(m_Cards == null) {
           lock(typeof(Deck)) {
               if(m_Cards == null) {
                   m_Cards = new ArrayList();
               }
           }
        }
        return m_Cards;
    }
}

That's a Check, Lock, Check, Load pattern for static initialisation.

Given that the variable is thread safe, you might be able to get away with Check, Load, but I couldn't find enough evidence to prove it one way or the other.

 

posted on Sunday, October 15, 2006 9:30 AM by admin

Powered by Community Server, by Telligent Systems