.netmultithreadingparadigmsdouble-checked-locking

Double-checked locking in .NET


I came across this article discussing why the double-check locking paradigm is broken in Java. Is the paradigm valid for .NET (in particular, C#), if variables are declared volatile?


Solution

  • Implementing the Singleton Pattern in C# talks about this problem in the third version.

    It says:

    Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!

    The author seems to imply that double locking is less likely to work than other strategies and thus should not be used.