singleton pattern

Discussion in 'Java' started by joe, Oct 25, 2004.

  1. joe

    joe Guest

    Typical i write my singletons like this:

    protected static MyClass singleton;
    protected MyClass() { }
    public static MyClass getInstance() {
    if( singleton == null ) {
    singleton = new MyClass();
    }
    return singleton;
    }


    However on more than once occasion I've come across this:
    protected static MyClass singleton = new MyClass();
    protected MyClass() {}
    public static MyClass getInstance() {
    return singleton;
    }

    Now for some reason the seconds way bothers me. I am not sure why ? Is
    there something to this ? Or I am just being stupid ?

    joe
     
    joe, Oct 25, 2004
    #1
    1. Advertising

  2. "joe" <> writes:

    > Typical i write my singletons like this:


    [lazy initialized singleton]

    > However on more than once occasion I've come across this:


    [singleton initialzed when class is loaded]

    > Now for some reason the seconds way bothers me. I am not sure why ? Is
    > there something to this ? Or I am just being stupid ?


    The difference between the two methods is that the latter creates the
    instance object when the class is loaded, and the former creates it
    the first time it is requested.

    The former has a small overhead each time the instance is requested,
    because it tests whether it is null. The latter is potentially wastefull
    if the instance is never requested.

    So, if you know that you *will* request the instance (and what other
    reason is there for loading a singleton class? :) then the latter is
    *probably* fine. You can even make the instance field "final" :)

    I also have an irrational preference for the lazily intialized
    singleton, but I can't think of any singleton class I have ever used,
    where I didn't request the singleton.

    /L
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Oct 25, 2004
    #2
    1. Advertising

  3. joe wrote:
    > Typical i write my singletons like this:
    >
    > protected static MyClass singleton;
    > protected MyClass() { }
    > public static MyClass getInstance() {
    > if( singleton == null ) {
    > singleton = new MyClass();
    > }
    > return singleton;
    > }
    >
    >
    > However on more than once occasion I've come across this:
    > protected static MyClass singleton = new MyClass();
    > protected MyClass() {}
    > public static MyClass getInstance() {
    > return singleton;
    > }
    >
    > Now for some reason the seconds way bothers me. I am not sure why ? Is
    > there something to this ? Or I am just being stupid ?
    >
    >


    The first way is not threadsafe - you might end up with more than one
    instance of the "Singleton" unless your accessor is synchronized.

    While the second example seems to create an instance even if the class
    in question is not used, it isn't normally so. Most JVMs don't load the
    class till some code makes a reference to it, and the instance will be
    created only during classloading. (And in almost all cases that I have
    encountered, the first access to a Singleton class is the getInstance()
    call)


    BK
     
    Babu Kalakrishnan, Oct 25, 2004
    #3
  4. joe

    Eric Sosman Guest

    joe wrote:
    > Typical i write my singletons like this:
    >
    > protected static MyClass singleton;
    > protected MyClass() { }
    > public static MyClass getInstance() {
    > if( singleton == null ) {
    > singleton = new MyClass();
    > }
    > return singleton;
    > }
    >
    > However on more than once occasion I've come across this:
    > protected static MyClass singleton = new MyClass();
    > protected MyClass() {}
    > public static MyClass getInstance() {
    > return singleton;
    > }
    >
    > Now for some reason the seconds way bothers me. I am not sure why ? Is
    > there something to this ? Or I am just being stupid ?


    First, I think you want `private' rather than
    `protected'. With the latter, it seems to me someone
    could do:

    class NoSingletonIsAnIsland extends MyClass {
    public static MyClass makeAnotherOne() {
    return new MyClass();
    }
    }

    .... and proceed to make a million instances of your
    "singleton" class.

    As to your fundamental question, both approaches
    have their place. If constructing the MyClass instance
    is expensive and there's a reasonable chance you won't
    ever need one, your "lazy initialization" style makes
    sense. However, you'll need more bullet-proofing to
    make it thread-safe; imagine what would happen if thread
    T1 was busy in the MyClass constructor (it's assumed to
    be expensive, so the constructor will take a while) and
    T2 came along, found `singleton' still null, and started
    constructing another one ... The second pattern avoids
    the synchronization issues at the cost of *always* making
    a MyClass instance, which would be a shame if it were
    expensive and it turned out you didn't need one after all.

    There's a discussion of both these patterns and of
    some further variants in "Effective Java" by Bloch.

    --
     
    Eric Sosman, Oct 25, 2004
    #4
  5. On Mon, 25 Oct 2004 18:52:39 +0200, Lasse Reichstein Nielsen wrote:
    > [lazy initialized singleton]


    > The former has a small overhead each time the instance is requested,
    > because it tests whether it is null.


    It also has a race condition that can only be solved by explicit
    synchronization, missing from the example.

    > [singleton initialzed when class is loaded]


    > The latter is potentially wastefull if the instance is never
    > requested.


    Since the instance won't be created until the class itself is loaded
    (which won't happen until it is needed at runtime), where is the
    potential for waste?

    The Java classloading mechanism already provides lazy initialization.
    There is no need to implement it yourself in this case.

    /gordon

    --
    [ do not email me copies of your followups ]
    g o r d o n + n e w s @ b a l d e r 1 3 . s e
     
    Gordon Beaton, Oct 25, 2004
    #5
  6. joe

    Doug Pardee Guest

    Babu Kalakrishnan <> wrote:
    > Most JVMs don't load the class till some code makes a reference to
    > it, and the instance will be created only during classloading.


    Not "most"... *all*. This is required by section 12.4.1 of the Java 2
    Language Specification.

    Also, to be pedantic:
    1) it's not the JVM that's involved, it's the ClassLoader, and
    2) the singleton instance is NOT created during classloading; it is
    created during class *initialization*.

    The ClassLoader is permitted to load (and possibly link) the class
    before it is needed, but the ClassLoader is *not* permitted to
    initialize the class, thus running the "new" statement, until the
    class is actually accessed.
     
    Doug Pardee, Oct 26, 2004
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Proton Projects - Moin

    Singleton - Whether Cloneable overrides Singleton

    Proton Projects - Moin, Mar 26, 2007, in forum: Java
    Replies:
    4
    Views:
    3,259
    Proton Projects - Moin
    Mar 27, 2007
  2. Wilhelm
    Replies:
    1
    Views:
    167
  3. Trans
    Replies:
    12
    Views:
    280
    Robert Klemme
    Sep 14, 2007
  4. Paul McMahon
    Replies:
    3
    Views:
    207
    David A. Black
    Jun 9, 2008
  5. Charles Oliver Nutter

    Singleton methods without the singleton class

    Charles Oliver Nutter, Mar 15, 2010, in forum: Ruby
    Replies:
    4
    Views:
    204
    Charles Oliver Nutter
    Mar 22, 2010
Loading...

Share This Page