Skip to content

Singleton pattern implementation

jrcc edited this page Jan 31, 2013 · 4 revisions

Here is a good MSDN article regarding thread-safe implementation of the Singleton pattern. Key points made in this article:

  1. Static initialization is preferred over explicit lazy initialization. Using static initialization, the CLR will ensure that the singleton is initialized only once, and only when actually required.

  2. If you choose to implement explicitly lazy initialization, you must use the double-checked locking pattern, and use the volatile keyword.

In addition to worrying about the thread-safety of the Singleton's instantiation, it is equally important to consider the thread-safety of the Singleton class itself. Use of a singleton in a multi-threaded application implies that the singleton object must be designed to be safe for concurrent use by multiple threads.

It is also worth mentioning that the singleton design pattern is often overused. Singleton classes can lock you in to a certain type of behaviour and cause unnecessary coupling between classes (see http://www-128.ibm.com/developerworks/webservices/library/co-single.html).

Clone this wiki locally