Re: Singleton Question

From: Chris Smith (cdsmith_at_twu.net)
Date: 06/30/04


Date: Wed, 30 Jun 2004 07:07:46 -0600

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


Relevant Pages

  • Re: RMI, singletons and multiple classloaders in Weblogic
    ... With the Singleton ... >>pattern, that registry is within the class itself. ... GoF pattern: I'd nominate one of "Decorator", "Template Method", or ... "Factory / Factory Method" for that honor. ...
    (comp.lang.java.programmer)
  • Re: Singleton Pattern
    ... I have a question about singleton pattern. ... the Plant class is now coupled to LightSourceSingletonFactory and the ... LightSource interface. ...
    (comp.lang.java.programmer)
  • Re: Singleton Question
    ... > Singleton is a pattern, ... > public class MySingletonClass ...
    (comp.lang.java.programmer)
  • Re: Singleton --- almost
    ... > Singleton because only one instance is needed: ... > design patterns to apply, instead of trying to judge which design patterns are ... > pattern is relatively easy to understand, ... It may be useful to have a registry of particular objects used by ...
    (comp.lang.java.programmer)
  • Re: Creating framework for singleton pattern?
    ... >> question the usefulness, in the long run, of the Singleton pattern. ... The wiki page has a long quote from Kent Beck, ... "The Singleton Design Pattern Does More Harm Than Good" ... misused by allowing the creation of global variables in an OO context, ...
    (microsoft.public.dotnet.languages.csharp)