title: Overzealous null checking of backing field in my singleton?
body: <p>The code below represents a singleton that I use in my application.  Lets assume that <code>_MyObject = New Object</code> represents a very expensive database call that I do not want to make more than once under any circumstance.  To ensure that this doesn't happen, I first check if the <code>_MyObject</code> backing field is null.  If it is, I break into a SyncLock to ensure that only one thread can get in here at a time.  However, in the event that two threads get past the first null check before the singleton is instantiated, thread B would end up sitting at the SyncLock while thread A creates the instance.  After thread A exits the lock, thread B would enter the lock and recreate the instance which would result in that expensive database call being made.  To prevent this, I added an additional null check of the backing field which occurs within the lock.  This way, if thread B manages to end up waiting at the lock, it will get through and do one more null check to ensure that it doesn't recreate the instance.</p>
  
  <p>So is it really necessary to do two null checks?  Would getting rid of the outer null check and just starting out with the Synclock be just the same?  In other words, is thread-locking a variable just as fast as letting multiple threads access a backing field simultaneously?  If so, the outer null check is superfluous.</p>
  
  <pre><code>Private Shared synclocker As New Object
  Private Shared _MyObject As Object = Nothing
  Public Shared ReadOnly Property MyObject As Object
      Get
          If _MyObject Is Nothing Then 'superfluous null check?
              SyncLock synclocker
                  If _MyObject Is Nothing Then _MyObject = New Object
              End SyncLock
          End If
  
          Return _MyObject
      End Get
  End Property
  </code></pre>