Threadsafe singleton using volatile,synchonized

Sean Kelly sean at f4.ca
Sat May 26 08:30:32 PDT 2007


BLS wrote:
> 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;
> }


No.  The 'volatile' qualifier is applied to a statement, not a variable. 
  You need to do something like this:

# class Singleton
# {
#     static Singleton s;
#
#     Singleton instance()
#     {
#         volatile Singleton tmp = s;
#         if(!tmp)
#         {
#            synchronized
#            {
#                tmp = s;
#                if(!tmp)
#                {
#                   volatile tmp = new Singleton();
#                   s = tmp;
#                }
#            }
#         }
#         return s;
#     }
# }

This is from:

http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=9260

in thread:

http://www.digitalmars.com/d/archives/digitalmars/D/9149.html#N9231


Sean



More information about the Digitalmars-d mailing list