Singleton Question

Discussion in 'Java' started by Dave Monroe, Jun 30, 2004.

  1. Dave Monroe

    Dave Monroe Guest

    Can somebody point me to a spec for singleton implementation?

    I'm working with an application that has a couple of singletons and
    obviously the member variables are kept separate in the threads that
    use the singleton, but I can't find any documentation that explains
    the rules.

    TIA

    Dave Monroe
     
    Dave Monroe, Jun 30, 2004
    #1
    1. Advertising

  2. Dave Monroe

    Chris Smith Guest

    Dave Monroe wrote:
    > Can somebody point me to a spec for singleton implementation?


    Singleton is a pattern, not a specification. There is a description of
    the general pattern on page 127 of GoF. In general, Java
    implementations use the static initialization time feature to avoid
    overhead when retrieving an object, as such:

    public class MySingletonClass
    {
    private static MySingletonClass instance = new MySingletonClass();

    public static MySingletonClass getInstance()
    {
    return instance;
    }

    private MySingletonClass() { }

    ...
    }

    Unlike similar-looking code in other languages, this will *not* create
    an instance of MySingletonClass until the first time getInstance is
    called (or the first time MySingletonClass is loaded directly from a
    classloader with an explicit request to initialize it). Essentially,
    lazy initialization is provided for you as a feature.

    > I'm working with an application that has a couple of singletons and
    > obviously the member variables are kept separate in the threads that
    > use the singleton, but I can't find any documentation that explains
    > the rules.


    What you're describing doesn't really sound like a Singleton at all.
    Singletons are shared objects, and are intended that way. They
    generally have little or no state at all, and thread-local state is
    certainly not a part of the pattern.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jun 30, 2004
    #2
    1. Advertising

  3. Chris Smith wrote:

    > Dave Monroe wrote:
    >
    >> Can somebody point me to a spec for singleton implementation?

    >
    >
    > Singleton is a pattern, not a specification. There is a description of
    > the general pattern on page 127 of GoF. In general, Java
    > implementations use the static initialization time feature to avoid
    > overhead when retrieving an object, as such:
    >
    > public class MySingletonClass
    > {
    > private static MySingletonClass instance = new MySingletonClass();
    >
    > public static MySingletonClass getInstance()
    > {
    > return instance;
    > }
    >
    > private MySingletonClass() { }
    >
    > ...
    > }


    My normal way in Singleton handling is instead:

    public class MySingletonClass
    {
    public static final MySingletonClass instance = new MySingletonClass();

    private MySingletonClass() { }

    ...
    }

    Which are pros and cons of my vs your way ?

    - Dario
     
    =?UTF-8?B?IkRhcmlvIChkcmlua2luZyBjb++sgGVlIGluIHRo, Jun 30, 2004
    #3
  4. Dave Monroe

    Chris Smith Guest

    Dario wrote:
    > Which are pros and cons of my vs your way ?
    >


    Not a lot. I guess I write a getXXX method because it more closely
    resembles the way singleton is often implemented in other languages.
    Either is equally valid, though.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jun 30, 2004
    #4
  5. Dave Monroe

    Lance Lamboy Guest


    >> public class MySingletonClass
    >> {
    >> private static MySingletonClass instance = new MySingletonClass();
    >>
    >> public static MySingletonClass getInstance() {
    >> return instance;
    >> }
    >> }
    >> private MySingletonClass() { }
    >>
    >> ...
    >> }
    >> }

    > My normal way in Singleton handling is instead:
    >
    > public class MySingletonClass
    > {
    > public static final MySingletonClass instance = new
    > MySingletonClass();
    >
    > private MySingletonClass() { }
    >
    > ...
    > }
    > }
    > Which are pros and cons of my vs your way ?


    I would recommend hiding accessing to the singleton through a public
    method. That way you preserve flexibility. You could update the
    previously mentioned MySingletonClass to the below code without anyone
    else having to change their code.

    public class MySingletonClass // used to be a singleton but changed for
    operational reasons
    {
    private static MySingletonClass a = new MySingletonClass(); private
    static MySingletonClass b = new MySingletonClass();

    public static MySingletonClass getInstance() {
    if ( delta ( ) return a ; )
    return ( b ) ;
    }
    }
    private static boolean delta ( ) { ... }

    private MySingletonClass() { }

    ...
    }
    }

    > - Dario


    --
    Lance Lamboy

    "Go F*ck Yourself" ~ Dick Cheney
     
    Lance Lamboy, Jun 30, 2004
    #5
  6. Dave Monroe

    Gorf Guest

    "Chris Smith" <> wrote in message
    news:...
    > Dario wrote:
    > > Which are pros and cons of my vs your way ?
    > >

    >
    > Not a lot. I guess I write a getXXX method because it more closely
    > resembles the way singleton is often implemented in other languages.
    > Either is equally valid, though.


    I do it a slightly different way, lazy instantiation...

    public class MySingletonClass {

    private static MySingletonClass instance;

    public static MySingletonClass getInstance() {
    if (instance == null)
    instance = new MySingletonClass();
    return instance;
    }

    private MySingletonClass() { }

    ...
    }

    It's got an if-statement in there, but for some reason, I like it this way
    :)

    --
    Gorf
     
    Gorf, Jun 30, 2004
    #6
  7. Dave Monroe

    Keith James Guest

    [...]

    Gorf> I do it a slightly different way, lazy instantiation...

    Gorf> public class MySingletonClass {

    Gorf> private static MySingletonClass instance;

    Gorf> public static MySingletonClass getInstance() {
    Gorf> if (instance == null)
    Gorf> instance = new MySingletonClass();
    Gorf> return instance;
    Gorf> }

    Gorf> private MySingletonClass() { }

    Gorf> ...
    Gorf> }

    Gorf> It's got an if-statement in there, but for some reason,
    Gorf> I like it this way :)

    Lazy, but not threadsafe. You're much better off with Chris'
    suggestion which is both.

    --

    - Keith James <> Microarray Facility, Team 65 -
    - The Wellcome Trust Sanger Institute, Hinxton, Cambridge, UK -
     
    Keith James, Jun 30, 2004
    #7
  8. Lance Lamboy wrote:

    > I would recommend hiding accessing to the singleton through a public
    > method. That way you preserve flexibility. You could update the
    > previously mentioned MySingletonClass to the below code without anyone
    > else having to change their code.


    Ok. Thanks.

    - Dario
     
    =?UTF-8?B?IkRhcmlvIChkcmlua2luZyBjb++sgGVlIGluIHRo, Jun 30, 2004
    #8
  9. Dave Monroe

    Chris Smith Guest

    Gorf wrote:
    > I do it a slightly different way, lazy instantiation...
    >


    Here's probably more than you want to know...

    The reason is rather subtle, but both of our pieces of code do lazy
    instantiation. If I write:

    public class MySingletonClass
    {
    private static MySingletonClass instance = new MySingletonClass();
    ...
    }

    That new object is created at class initialization time. In Java, class
    initialization happens directly prior to the first access to the class,
    and *not* at the beginning of the application.

    Java is primarily designed that way because there's no way for the JVM
    to know all the classes that will be used when the application first
    begins -- as opposed to many other languages where an explicit link step
    provides this information. In this case, though, we can take advantage
    of this fact (which is specified, and therefore guaranteed) to delay
    initialization of a singleton instance.

    The primary advantage of the code as I wrote it above is that it is
    implicitly thread-safe to retrieve the singleton instance. You could
    provide this thread-safety explicitly in your version by synchronizing
    the getInstance method, but there are several reasons it's at least
    marginally better to go with class initialization:

    1. The thread synchronization for class initialization is going to
    happen anyway (to set your instance field to null, for example),
    so you'd just be introducing redundant synchronization.

    2. Synchronization can be done better by the JVM. It knows that
    class initialization can only happen once, so it can (and almost
    certainly does) actually mutate the code so that there is zero
    cost for the synchronization after class initialization is
    complete.

    You may not be working in a multithreaded environment (although that's
    hard to imagine in Java), or you might not be concerned about
    performance, but when the better and faster technique is also easier to
    read and write, it makes a good default to use that technique.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jun 30, 2004
    #9
  10. Dave Monroe

    GaryM Guest

    Keith James <> wrote in
    news::

    >
    > Lazy, but not threadsafe. You're much better off with Chris'
    > suggestion which is both.
    >


    Not to go off on a tangent, but I was reading about double check
    locks recently. Does this make his example thread safe:

    if (instance == null) {
    synchronized(this) {
    if(instance == null)
    instance = new MySingletonClass();

    }
    }
    return instance;
     
    GaryM, Jun 30, 2004
    #10
  11. Dave Monroe

    Phillip Lord Guest

    >>>>> "GaryM" == GaryM <> writes:

    GaryM> Keith James <> wrote in
    GaryM> news::

    >>
    >> Lazy, but not threadsafe. You're much better off with Chris'
    >> suggestion which is both.
    >>


    GaryM> Not to go off on a tangent, but I was reading about double
    GaryM> check locks recently. Does this make his example thread safe:

    GaryM> if (instance == null) {
    GaryM> synchronized(this) {
    GaryM> if(instance == null)
    GaryM> instance = new
    GaryM> MySingletonClass();

    GaryM> }
    GaryM> }
    GaryM> return instance;

    I don't think that you can use a "this" reference here. The factory
    method is in the static context, so there is not this.


    All of this is unnecessary. Without any of this, still the instance
    will only be created when the class is loaded. This will happen the
    first times it's referenced in a static context, which you have to do
    to get to the instance.

    So the class loader already provides you with lazy instantiation, and
    more over provides you with synchronisation. There is just no point to
    what you are doing.

    Cheers

    Phil
     
    Phillip Lord, Jun 30, 2004
    #11
  12. GaryM wrote:

    > Keith James <> wrote in
    > news::
    >
    >> Lazy, but not threadsafe. You're much better off with Chris'
    >> suggestion which is both.
    >>

    >
    > Not to go off on a tangent, but I was reading about double check
    > locks recently. Does this make his example thread safe:
    >
    > if (instance == null) {
    > synchronized(this) {
    > if(instance == null)
    > instance = new MySingletonClass();
    >
    > }
    > }
    > return instance;


    There is not 'this' in a static method.
     
    =?UTF-8?B?IkRhcmlvIChkcmlua2luZyBjb++sgGVlIGluIHRo, Jun 30, 2004
    #12
  13. Dave Monroe

    Chris Smith Guest

    GaryM wrote:
    > Not to go off on a tangent, but I was reading about double check
    > locks recently. Does this make his example thread safe:
    >
    > if (instance == null) {
    > synchronized(this) {
    > if(instance == null)
    > instance = new MySingletonClass();
    >
    > }
    > }
    > return instance;


    No. Never do that. It was an interesting idea, and got spread around
    by a lot of people that appreciated how clever it is. We're now in the
    stage of growing realization that double-checked locking is inherently
    broken in most cases.

    Incidentally, this can be made safe, but only on a platform with a known
    architecture where:

    1. There is a strict memory order observed by the hardware platform.

    OR

    2. You can insert memory barriers at appropriate places to prevent
    reordering of memory accesses.

    Since Java neither guarantees such hardware nor provides any way of
    inserting memory barriers (except from entering or leaving a
    synchronized block or method, which will generate memory barriers as
    needed for the target hardware), you can't do this in Java. You can't
    do it in any portable high-level language, though it's possible in a mix
    of some non-Java languages with assembly if you assume a target
    hardware.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jun 30, 2004
    #13
  14. Dave Monroe

    GaryM Guest

    GaryM, Jun 30, 2004
    #14
  15. Dave Monroe

    Roedy Green Guest

    On 30 Jun 2004 05:33:38 -0700, (Dave Monroe)
    wrote or quoted :

    >I'm working with an application that has a couple of singletons and
    >obviously the member variables are kept separate in the threads that
    >use the singleton, but I can't find any documentation that explains
    >the rules.


    Design Patterns are not like code or collections. The rules are fuzzy,
    and more rules of thumb.

    A singleton is by definition unique. It can't have separate variables
    for separate threads. So any use of its variables must be shared by
    the threads that use it. That means synchronisation to make the
    singleton thread safe.

    This is more a thread issue than a singleton issue.

    see http://mindprod.com/jgloss/thread.html
    http://mindprod.com/jgloss/threadsafe.html

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #15
  16. Dave Monroe

    Roedy Green Guest

    On 30 Jun 2004 05:33:38 -0700, (Dave Monroe)
    wrote or quoted :

    >I'm working with an application that has a couple of singletons and
    >obviously the member variables are kept separate in the threads that
    >use the singleton, but I can't find any documentation that explains
    >the rules.


    see http://mindprod.com/jgloss/singleton.html

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #16
  17. Dave Monroe

    Roedy Green Guest

    On 30 Jun 2004 17:49:09 +0100, Phillip Lord <>
    wrote or quoted :

    >So the class loader already provides you with lazy instantiation, and
    >more over provides you with synchronisation. There is just no point to
    >what you are doing.


    Why might you want to postpone creating the singleton past class load
    time?

    You might have such a case for example if you had a JCE or JDBC-like
    scheme for every driver to load sufficiently to register itself. You
    just want the stub there, not the works. You could do that of course
    by spitting off the registering stuff into its own class and not
    touching the singleton class.





    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #17
  18. Dave Monroe

    Roedy Green Guest

    On Wed, 30 Jun 2004 11:29:57 -0600, Chris Smith <>
    wrote or quoted :

    >2. You can insert memory barriers at appropriate places to prevent
    >reordering of memory accesses.


    Is not declaring instance volatile sufficient to make the JVM do
    whatever is necessary to avoid such out of order accesses?

    The big problem with threads is that any idea you come up with will
    work MOST of the time.
    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jun 30, 2004
    #18
  19. Dave Monroe

    Dave Monroe Guest

    Chris Smith <> wrote in message news:<>...
    > Dave Monroe wrote:
    > > Can somebody point me to a spec for singleton implementation?

    >
    > Singleton is a pattern, not a specification. There is a description of
    > the general pattern on page 127 of GoF. In general, Java


    What's GoF?

    > implementations use the static initialization time feature to avoid
    > overhead when retrieving an object, as such:
    >
    > public class MySingletonClass
    > {
    > private static MySingletonClass instance = new MySingletonClass();
    >
    > public static MySingletonClass getInstance()
    > {
    > return instance;
    > }
    >
    > private MySingletonClass() { }
    >
    > ...
    > }
    >
    > Unlike similar-looking code in other languages, this will *not* create
    > an instance of MySingletonClass until the first time getInstance is
    > called (or the first time MySingletonClass is loaded directly from a
    > classloader with an explicit request to initialize it). Essentially,
    > lazy initialization is provided for you as a feature.
    >
    > > I'm working with an application that has a couple of singletons and
    > > obviously the member variables are kept separate in the threads that
    > > use the singleton, but I can't find any documentation that explains
    > > the rules.

    >
    > What you're describing doesn't really sound like a Singleton at all.
    > Singletons are shared objects, and are intended that way. They
    > generally have little or no state at all, and thread-local state is
    > certainly not a part of the pattern.


    They're singletons - trust me.
     
    Dave Monroe, Jul 1, 2004
    #19
  20. Dave Monroe <> scribbled the following:
    > Chris Smith <> wrote in message news:<>...
    >> Dave Monroe wrote:
    >> > Can somebody point me to a spec for singleton implementation?

    >>
    >> Singleton is a pattern, not a specification. There is a description of
    >> the general pattern on page 127 of GoF. In general, Java


    > What's GoF?


    Gang of Four. A nickname for the book "Design Patterns" by Eric Gamma
    and a bunch of other guys.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
    "Nothing lasts forever - so why not destroy it now?"
    - Quake
     
    Joona I Palaste, Jul 1, 2004
    #20
    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,308
    Proton Projects - Moin
    Mar 27, 2007
  2. Wilhelm
    Replies:
    1
    Views:
    179
  3. Trans
    Replies:
    12
    Views:
    292
    Robert Klemme
    Sep 14, 2007
  4. Paul McMahon
    Replies:
    3
    Views:
    216
    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:
    215
    Charles Oliver Nutter
    Mar 22, 2010
Loading...

Share This Page