Singleton Pattern

Jonathan M Davis jmdavisProg at gmx.com
Thu Jan 5 17:04:20 PST 2012


On Thursday, January 05, 2012 22:15:32 asm wrote:
> how can i implementing the singleton pattern in D?

The same way that you would in C++ or Java, except that unlike you have static 
constructors that you can use to initialize them, and unlike both, if it's not 
shared, then it's a singleton per thread and no locking is required.

If you're dealing with a multi-threaded singleton, technically, it should be 
possible to use double-checked locking with shared, but apparently bugs with 
shared make that unsafe at present. So, if you didn't initialize it in a 
shared static constructor, either you lock every time that you fetch the 
singleton or you use an extra bool for indicating that it's been initialized.

Single threaded:

T singleton()
{
 static T instance;

 if(!instance)
 instance = new T();

 return instance;
}

Multi-threaded:

shared(T) singleton()
{
 static shared T instance;
 static bool initialized = false;

 if(!initialized)
 {
 synchronized
 {
 if(!instance)
 instance = new shared(T)();
 }

 initialized = true;
 }

 return instance;
}

Once the bugs with shared with regards to fences have been fixed though, the 
shared version can look more like

shared(T) singleton()
{
 static shared T instance;

 if(!instance)
 {
 synchronized
 {
 if(!instance)
 instance = new shared(T)();
 }
 }

 return instance;
}

Regardless, if you use a shared static constructor, you can avoid the locking 
(it's just not lazily initialized then), and of course, the singly threaded 
one can use a static constructor if you don't care about lazy initialization. 
If you use a static constructor though, the instance would not be declared 
inside the singleton function (and it doesn't have to be here either - it's 
just shorter to do it this way in an example).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list