[Mono-list] Class library developers: locking issues to keep in mind

Serge serge@wildwestsoftware.com
Mon, 29 Oct 2001 16:16:49 +0200


Exactly, this is the correct solution (albeit only for static fields). This
is also solution mentioned by William Pugh.
However, taking into account current behaviour of both C# compiler and
runtime, the following little change is needed for C# version:

class Singleton {
 private static class SingletonHolder {
      static readonly Singleton singleton;

      // required!
      static SingletonHolder () {
       singleton = new Singleton();
      }
 }

 public static Singleton GetHeavyObject() {
      return SingletonHolder.singleton;
 }
}

This way (explicit static constructor) BeforeFieldInit will be ommited and
instance will be created on-demand.
And with line like this:
 static readonly Singleton singleton = new Singleton();
Compiler will create static constructor itself, enable BeforeFieldInit, and
instance will be initialized sometimes before the first access.
This is the subtle difference between Java and .NET initialization
sequences.
All in all, explicitly provided static constructor is always needed if you
want Java-like delayed initialization.

Thanks,
Sergey



----- Original Message -----
From: "Alexander Klyubin" <klyubin@aqris.com>
To: <mono-list@ximian.com>
Sent: Monday, October 29, 2001 3:50 PM
Subject: Re: [Mono-list] Class library developers: locking issues to keep in
mind


> Just browsed Joshua Bloch's Effective Java (ISBN: 0201310058). He also
> states that DCL is broken in Java. As one of the solutions in item #48
> initialize-on-demand holder class idiom is proposed. Applied to our
> situation it looks like this:
>
> class Singleton {
>    private static class SingletonHolder {
>      static final Singleton singleton = new Singleton();
>    }
>
>    public static Singleton GetHeavyObject() {
>      return SingletonHolder.singleton;
>    }
> }
>
> It uses Java's feature that class (SingletonHolder) is not initialized
> until it is first used. What this essentially means is that new
> Singleton() will be executed on first invocation of GetHeavyObject, not
> earlier.
>
> Alexander Klyubin
>