Threadsafe singleton using volatile,synchonized

BLS nanali at foo.fr
Sat May 26 01:47:54 PDT 2007


Probabely I should use D-Learn instead but due to the fact that it is about compiler optimizing ... blah, blah ; Simple question : Is this singleton implementation thread safe ?  Makes : 
static volatile Singleton _instance
sense ?

module pattern.singleton

class Singleton 
{
public:
	static Singleton getInstance()
	{
		// double check lock
        if (_instance is null)
		{
			synchronized {
                if (_instance is null) 
				{
                    _instance = new Singleton();
                }
            }
        }
        return _instance;      
    }
private:
	this() {} 
	
	// do not optimize  
	static volatile Singleton _instance;
}

Bjoern



More information about the Digitalmars-d mailing list