Skip to content

Instantly share code, notes, and snippets.

@xavierzwirtz
Last active December 19, 2016 21:09
Show Gist options
  • Select an option

  • Save xavierzwirtz/aa8f3372c37ae74b059793631b275f41 to your computer and use it in GitHub Desktop.

Select an option

Save xavierzwirtz/aa8f3372c37ae74b059793631b275f41 to your computer and use it in GitHub Desktop.

Made a discovery with the tech products site. The lazy load pattern that we typically use is not thread safe. In the appcon we had the property

Public Shared ReadOnly Property GetAppCon() As AppCon
    Get
        If m_oAppController Is Nothing Then
            m_oAppController = New AppCon()
        End If
        Return m_oAppController
    End Get
End Property

Which, if accessed multiple times before m_oAppController is set to a value would cause the site to start multiple database spinups.

Could fix it by wrapping it in synclocks, but that is verbose, and error prone if you dont do it exactly correct.

.Net provides System.Lazy for this exact case:

Private Shared ReadOnly _appCon As New Lazy(Of AppCon)(Function() New AppCon())

Public Shared ReadOnly Property GetAppCon() As AppCon
    Get
        Return _appCon.value
    End Get
End Property

It encapsulates all of the logic needed to make this thread safe, and make sure that the value is initialized exactly once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment