Singleton question (shared class)

Andrew Wiley wiley.andrew.j at gmail.com
Wed Jan 25 15:40:09 PST 2012


On Wed, Jan 25, 2012 at 9:35 AM, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> On Wed, 25 Jan 2012 09:50:57 -0500, Mars <- at -.-> wrote:
>
>> Alternative approach, I just found:
>> http://pastie.org/private/1jlcvfostnbopfp3quflg
>> If I get that right, this is basically the classic singleton, like it
>> would be in other languages, right?
>> So... what's the best way?
>
>
> This is an ok approach, but you must handle all threading issues manually.
>  In fact, you need to even with the shared version.  I don't know how
> threading support works with MySQL, so it may be ok just to ignore threading
> issues.  I'm not sure.
>
> Another approach is to use thread local storage to have a singleton per
> instance.  This avoids the whole problem of sharing the instance.
>
> An issue with your singleton allocation, is that you don't do the check for
> the instance being null while synchronized.  The singleton pattern looks
> like this:
>
> static T instance;
>
> T get()
> {
>   if(instance is null)
>   {
>      synchronized if(instance is null)
>      {
>          instance = new T;
>      }
>   }
>   return instance;
> }
>
> The second check is necessary to avoid allocating multiple instances (they
> will get thrown away, but no need to create them).
>
> Normally, you'd mark instance as volatile, but D2 doesn't support volatile
> any more.  I don't know the correct way to make sure the second check isn't
> optimized out.

In the language spec, shared is supposed to guarantee this, but it
currently doesn't. There was a conversation where pretty much every
safe variant of the singleton pattern was discussed recently:
http://www.digitalmars.com/d/archives/digitalmars/D/learn/Singleton_Pattern_31406.html


More information about the Digitalmars-d-learn mailing list