Results 1 to 3 of 3

Thread: Singleton

  1. #1
    dardar is offline Member
    Join Date
    Jan 2010
    Posts
    8
    Rep Power
    0

    Default Singleton

    i founr this implementation :
    public class Singleton
    {
    // Private constructor suppresses generation of a (public) default constructor
    private Singleton() {}

    /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance()
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
    private static class SingletonHolder
    {
    private final static Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance()
    {
    return SingletonHolder.INSTANCE;
    }
    }

    i cant understand how only one Instance of the class is created?
    if we call SingletonHolder twice it seems that there will be 2 object created.
    what am i missing here?

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,010
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by dardar View Post
    i cant understand how only one Instance of the class is created?
    if we call SingletonHolder twice it seems that there will be 2 object created.
    what am i missing here?
    I find that quite an obscure way to implement a singleton; I normally do it like this:

    Java Code:
    public class Singleton {
       private Singleton instance= new Singleton();
       public Singleton getInstance() { return instance; }
       ...
       private Singleton() { ... }
    }
    There are a few problems with this class: if several class loaders are used several 'singletons' are created. If the Singleton class isn't used but loaded the singleton is still eagerly created.

    kind regard,

    Jos

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default

    All the first version is doing is avoiding the eager loading.
    However, from my point of view, there's rarely if ever anything else in a Singleton that would result in it being loaded prior to a call to getInstance(), so I don't really see the value in the SingletonHolder style.

    Now someone'll come along and point out something...:)

Similar Threads

  1. Replies: 2
    Last Post: 10-06-2008, 09:06 PM
  2. singleton object ...
    By haiforhussain in forum Advanced Java
    Replies: 8
    Last Post: 06-23-2008, 06:43 AM
  3. Replies: 0
    Last Post: 03-29-2008, 12:41 PM
  4. Replies: 0
    Last Post: 09-26-2007, 08:32 PM
  5. singleton pattern
    By Peter in forum Advanced Java
    Replies: 1
    Last Post: 07-09-2007, 04:45 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •