3

I've the following code. It may be dumb question, but I'm not sure, if synchronization is necessary or not.


class MyClass
{
  [ThreadStatic]
  private static object _staticObject;
  private static readonly LockStaticField = new object();

  public static object StaticObject
  {
     get
     {
        lock(LockStaticField)
        {
           return _staticObject ?? (_staticObject = new object());
        }
     }
  }
}

I know ThreadStatic fields doesn't need any synchronization because the state is not shared. But what is about the static getter and the initialization?

DHN
  • 4,807
  • 3
  • 31
  • 45

1 Answers1

8

I know ThreadStatic fields doesn't need any synchronization because the state is not shared. But what is about the static getter and the initialization?

This, too, would not need locking to synchronize, as the data (the backing field) will be unique per thread. You can safely remove the lock here.

Note that, as of .NET 4, you may want to also consider using ThreadLocal<T> instead of [ThreadStatic] to hold any local thread data. There are a few advantages, both in terms of usage (ie: IsValueCreated), but also cleanup, as you can call Dispose() to clean up all instances on all threads directly.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Well, let's consider a long running initialization, which will be interupted definitely by the scheduler. (Yes I know that I should not call such an initialization in a getter. It's just a hypothetical scenario.) – DHN Jul 17 '12 at 07:11
  • @DHN Wouldn't matter still, as only *that thread* would be effected, and it'd be blocked during the initialization anyways. – Reed Copsey Jul 17 '12 at 15:55