Double-checked locking in .NET

Double-checking locking now works in Java as well as C# (the Java memory model changed and this is one of the effects). However, you have to get it exactly right. If you mess things up even slightly, you may well end up losing the thread safety.

As other answers have stated, if you’re implementing the singleton pattern there are much better ways to do it. Personally, if I’m in a situation where I have to choose between implementing double-checked locking myself and “lock every time” code I’d go for locking every time until I’d got real evidence that it was causing a bottleneck. When it comes to threading, a simple and obviously-correct pattern is worth a lot.

Leave a Comment