Is this multi-threaded Singleton more efficient?

I have a high-performance Singleton in a multi-threaded environment. Normally I would do something like this:

public static Foo GetInstance()
{
    lock (Foo._syncLock)
    {
        if (Foo._instance == null)
            Foo._instance = new Foo();
        return Foo._instance;
    }
}

I am wondering if the following will be more efficient instead, since it will avoid the continuous blocking of the thread, or is there a hidden problem with it?

public static Foo GetInstance()
{
    if (Foo._instance != null)
        return Foo._instance;
    lock (Foo._syncLock)
    {
        if (Foo._instance == null)
            Foo._instance = new Foo();
        return Foo._instance;
    }
}
+4
source share
2 answers

I am wondering if the following will be more efficient instead, since it will avoid the continuous blocking of the thread, or is there a hidden problem with it?

: " , ?" , . ! , , , .

: " , ?".

"", , .

"" , : " , ?"

"" , .

"", : " ?"

, "" , , , . , .

, "" , , " ?

, . -.

"" , .

:

?

. , , . :

static object sync = new object();
static bool b = false;
static int x = 0;
static int GetIt()
{
  if (!b)
  {
    lock(sync)
    {
      if (!b)
      {
        b = true;
        x = ExpensiveComputation();
      }
    }
  }
  return x;
}

, ? ! . , x , b true x 123, b, get true x.

, ? :

  • . .
  • , - Jon Skeet.
  • Lazy<T>.
  • .
  • , , , , InterlockedCompareExchange.
  • .
+9

- ! ... :

:

if(_instance == null)
  lock(_syncRoot)
    if(_instance == null)
      _instance = new Foo();

return _instance;

, , .

, . .

, , Singleton parallel.

Edit

: . , locking.

private static Foo _instance = new Foo();

, ... , , .

0

All Articles