[Mono-devel-list] What to do with TypeInitialization in case of exceptions on second attempt to access class ? Singleton pattern

Jonathan Pryor jonpryor at vt.edu
Mon Oct 25 21:55:10 EDT 2004

On Mon, 2004-10-25 at 17:49, Ben Maurer wrote:
> However, if you have a multi-threaded app, it is best to optimize this
> pattern. There are a few ways to do this:
> 1) Use Interlocked.CompareExchange
> if (Singleton.instance == null)
>     Interlocked.CompareExchange (ref Singleton.instance, new Singleton (), null);
> return Singleton.instance
> This is the fastest thread-safe way to do it. 
> 2) use the double-checked lock
> If you declare Singleton.instance as `volatile' and do
> if (Singeton.instance == null)
>     lock (typeof (Singeton)
>        if (Singleton.instance == null)
>              Singleton.instance = new Singleton ();
> The only advantage of this over 1 is that there is 0 chance that two
> singletons will be created and that one gets thrown away. If singleton
> is extremely expensive to initialize (or has side affects), you can use
> this rather than 1.

And then there's the easiest way to ensure that you only get one
instance, and it doesn't require any explicit locking: use the static

	private static Singleton instance = new Singleton();

But that's what got us into this conversation in the first place.

As a note, this is the only safe way to create a singleton in Java
(before their major memory model re-write).

It also has all the benefits of the other techniques -- the singleton is
created lazily (unless beforefieldinit is set, in which case things can
get optimized, and optimization is good anyway), only one instance is
ever constructed, and you don't need to worry about locking (the runtime
handles it).  What could be nicer?

 - Jon

More information about the Mono-devel-list mailing list