Static Singleton Interface

Discussions

J2EE patterns: Static Singleton Interface

  1. Static Singleton Interface (40 messages)

    I've been using this pattern (possibly best practice) a lot lately and haven't noticed it documented anywhere. I'm sure many of you have implemented this same idea, hence the pattern designation.

    I resort to Singletons when I have a service that just can't be cleanly implemented as a purely static class.

    I would conventionally implement a Singelton as such:
    <pre>
    public class Singelton {
      private static instance Singleton = new Singleton();

      private Singleton() {}

      public static Singleton getInstance() {
        return instance;
      }

      public Object getField() {
        return someField;
      }
    }
    </pre>

    and the client would access it like this:
    <pre>
    Singelton.getInstance().getField();
    </pre>

    The getInstance() always struck me as an unnecisary step for the client, so I've arrived at this solution, the heart of this pattern:
    <pre>
    public class Singelton {
      private static instance Singleton = new Singleton();

      private Singleton() {}

      public static Object getField() {
        return instance.someField;
      }
    }
    </pre>

    and the client would access it like this:
    <pre>
    Singelton.getField();
    </pre>

    As you can see, this does not limit you in any way, while it simplifies the API for your client.

    Threaded Messages (40)

  2. Static Singleton Interface[ Go to top ]

    I use the same for UUID creation :

    I prefre to write : UUID.nextID() rather
    than UUID.getInstance().nextID()

    public class UUID {

        private static UUID instance = new UUID();

        public static UUID getInstance() {
            return instance;
        }

        public static String nextID() {
            return getInstance().internalNextID();
        }

        private UUID() { ... }

        private String internalNextID() { ... }

        ....

    }

    bye

  3. Static Singleton Interface - Vijay DY[ Go to top ]

    Hey Bob :
      
    I found your pattern interesting at the same time I want to put forward some of the issues which concerns me with this approach.

    1. As a matter of fact, the piece of code never gets compiled.
    2.Leaving that and considering the approach, how do you ensure the singleton class's the "instance" is thread safe. Assuming there's a situation where in two threads try to instantiate this class concurrently, may result in non availability of the class and that results in null pointer exception. So, we need to synchronize the constructor inorder to eliminate the uncertainity of such scenarios. Or can make all the threads to wait till the first time instatiation of singelton class takesplace. Probably, you must be knowing abt. this fact, or you would have just left it for the discussion.
    3.There's no necessary to call everytime the getInstance() method for getField(). As because the getField() method is a static you can directly give a call to this method by Singleton.getField() instead accessing through the instance.

    Can you pls. tell me any particular scenario, where in you don't need a singleton class to be a static. I have no doubt in the above approach but just out of my curiosity I would like to know. And FYI, this approac is already dealt as "lazy-Singleton" much before.

    I would appreciate if you can throw some more light on this.
  4. Static Singleton Interface - Vijay DY[ Go to top ]

    Your last issue can besolved by instatiating with a piece of static class code. Since the class loader is always synchronized. It'll be impossible to instatiate the class twice
  5. Static Singleton Interface - Vijay DY[ Go to top ]

    The constructor does not need to be synchronized! Why do you answer questions when you haven't got a clue to how it works? You probably read somewhere that double checked locking (DCL) does not work in java (which is correct). You need to synchronize the methods on a singleton class properly if you know you're going to have different threads competing to read and write state of the singleton instance.
  6. The entire point of having a getInstance is that you preserve the class as an object - rather than simply global functions within modular programming.

    This is not OO purism, but a very pragmatic approach to code reuse. The object may be instantiated as an object rather than simply used as a singleton providing the getInstance() mechanism is used.

    In my experience, this has never been required, but its worth doing just incase. Typing getInstance() is hardly a great inconvenience, and even less so within an IDE.

    Basically your pattern is lazy coding. Don't do it.

    Jonathan
  7. Static Singleton Interface - Vijay DY[ Go to top ]

    test...

    public class DataAccessManager {

      private AbstractDataSource ads;

      public DataAccessManager(){}
    }
  8. Static Singleton Interface - Vijay DY[ Go to top ]

    Vijay,

    Actually, I believe "lazy-singleton" refers to a Singleton that uses lazy initialization.

    Correct me if I'm mistaken.

    Bob
  9. Static Singleton Interface - Vijay DY[ Go to top ]

    I guess I'm just not getting the point. You want a static class. Why not use a static class? Just use all static memeber members. Why are you putting all this though and effort into writing a static class in a way that is going to be more difficult for your replacement to understand? (giggle)
  10. You're absolutely right, it just does not compile.
    But if you look at it, let's say 6 secs, you'll see that the problem is someway easy to solve :
    change the class name in "Singleton" instead of "Singelton"

    public class Singleton {
      
      Object someField=null;

      private static Singleton instance = new Singleton();

      private Singleton() {}

      public static Object getField() {
        return instance.someField;
      }
    }
  11. What if you wanted to pass a reference to this singleton around to another class? getInstance()? ;)
  12. Static Singleton Interface[ Go to top ]

    How is your Singleton different than simply having a purely static (functional class)? Why do you bother having a static instance attribute?

    The big advantage of using getInstance() to access the singleton is so that the actual instance implementation can be hidden. If you use a static class to implement a Singleton, then you are stuck with a static implementation.

    Marko.
    .
     
  13. Static Singleton Interface[ Go to top ]

    Marko,

    I do agree with u.
    can u talk abt when we should use Singleton and
    when we should use purely static utility class?
  14. Static Singleton Interface[ Go to top ]

    Their is no doubt you can get this to work. But why? To prevent the user from needing to use a factory method? If anything the factory method hides how the object is being created without implying anything, which is a good thing.

    Also, you can't have your static class implement an interface. What happens when you want to extend you singleton class?

    What are you gaining?
  15. Static Singleton Interface[ Go to top ]

    First, it is a Singleton, not a factory. There are no factory implementation details to hide.

    Secondly, the static class is the interface. If you want to plug in new implementations you can.

    If you think your class will have to support other interfaces or be treated as a normal object don't use this pattern.

    Also, this keeps you from having to worry about "clone()"s or other possible traps. What if you wanted to use lazy initialization on your Singleton? What if you cached your Singleton using a SoftReference or some other method for caching? Allowing clients the ability to make and keep hard references to your instance breaks this.

    Lastly, this keeps unnecisary explicit "getInstance()" (there's only one instance after all) methods from polluting your code. It's not to appease lazy coders or programmers with an aversion to IDE's. It's to make for clean, readable code.

    Adding a "getInstance()" does not make it any more OO.

    In regard to synchronization, proceed as you would with a normal Singleton.

    Bob
  16. Static Singleton Interface[ Go to top ]

    Here's an example.

    I personally used this pattern to make a class to provide environment information (server addresses, resource locations, development stage, etc.). The class offers up different information depending on the environment (development, test, or production). We don't have to make any code or configuration changes as we migrate code between environments.

    IMHO, Environment.getContentServerAddress() is cleaner than Environment.getInstance().getContentServerAddress().

    Using this method allowed me to abstract out the implementation details behind how the data is retrieved (i.e. JNDI, properties files, xml files, etc.).

    I also added methods to check what stage we were in. I often use these to customize error messages between the stages (for example, in development, I print stack traces).

    This isn't a class that we will ever need to extend upon or pass around as an object.

  17. Static Singleton Interface[ Go to top ]

    I don't like to put static initializers or static blocks, such as:

    static private void mInstance = new Object();

    or
    { //static scope
        mInstance = new Objet();
    }

    Simply because you put your code at the mercy of the classloader. Generally you cannot control classloader timing, expecially in a J2EE container, hence you do not know WHEN you static instance will be initiated at runtime.

    Instead you should lazy-initiation (synchronized getInstance()), or use the ThreadLocal Singleton pattern if ou are afraid of synchronization performance inssues.

    Gene
  18. Static Singleton Interface[ Go to top ]

    I always thought the point of a singleton was to hide the fact that you were using a static class from the client using it. I see no way of doing this with your current approach, your singleton will always be a "static" class. As far as i can see you cannot convert it to refer to a pool of objects or to just regular class without refactoring the client code. You also cannot lazy load or what not.
    The whole power of the Singleton is it's getInstance() method.
    Your
    <pre>
    public class Singelton {
      private static instance Singleton = new Singleton();

      private Singleton() {}

      public static Singleton getInstance() {
        return instance;
      }

      public Object getField() {
        return someField;
      }
    }
    </pre>

    should look like this
    <pre>
    public class Singelton {
      private static instance Singleton =null;

      private Singleton() {}

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

      public Object getField() {
        return someField;
      }
    }
    </pre>


    so to convert to instance class we just do this


    public static Singleton getInstance() {
      return new Singleton();
    }

    Jeff Anderson
  19. Static Singleton Interface[ Go to top ]

    As was previously stated, you should only do this with classes that you know will remain Singleton. Also, you can implement lazy initialization.
  20. Static Singleton Interface[ Go to top ]

    I see your point but things always seem to get extended later in ways unforeseen in the original development. In our case, we originally developed a PropertyManager similar to what you describe. Later on, the requirement came up to support many different portals simultaneously. Suddenly a pure singleton is no longer the most convenient way to do it. It seems to me that the getInstance pattern allows you to hide whether it's really a singleton or what I call a "multipleton" - almost a singleton but there may be more than one of them for various reasons.
  21. Static Singleton Interface[ Go to top ]

    /*remebmber to make the getInstance method synchronised
    or your code is not thread safe...
    should look like this ...
    <pre> */
    public class Singelton {
      private static instance Singleton =null;

      private Singleton() {}

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

      public Object getField() {
        return someField;
      }
    }
    </pre>
    //best regards krystian
  22. Static Singleton Interface[ Go to top ]

    All this singleton stuff is ridiculous !!!!

    WHY ? WHY ? WHY IN THE WORLD DO U NEED AN INSTANCE OF THE CLASS I.E. IF U ONLY NEED ONE, USE THE BLOODY CLASS ITSELF

    Go to IBM's site and look a nice article by Peter Haggar (Article dated : May 2002) that states that "singleton" is a failed programming idiom. The article has elaborated with examples of how a singleton can screw up. Don't go blindly for fancy programming idioms. They may look fashionable and trendy to speak in u'r developer circles but they sometimes expose u'r ass too. So watch it !!

    I have implemented the "EJBHomeCache" pattern but WITHOUT the singleton. INSTEAD of the single instance of the cache class, THE CLASS ITSELF ACTS AS THE SINGLETON. Believe Me, the pattern shown below works perfectly fine in an application (Single EJB Server) that has more than 1100 Web components!!
    PLEASE don't try this stuff inside the EJBs. Instead cache u'r homes as instance variables in u'r session beans by looking them up only once in the setSessionContext. This pattern is for Web tier only. U can Use this class directly AS IS or wrap access to it up in some high level object that all the components in u'r application uses, so those components don't have to import this class. Only that high level class of your application has to import this class.

    //////////// pattern //////////

    import java.util.HashMap;
    import javax.naming.InitialContext;
    import javax.ejb.EJBHome;
    import javax.naming.NamingException;

    public class LookUpCache
    {

        public static synchronized EJBHome getEJBHome(String jndiNameOfEjb) throws NamingException
    {
    EJBHome ejbHome = (EJBHome) hashMap.get( jndiNameOfEjb );

    // If its not in the global Hashtable,
    if(ejbHome == null)
    {
    // Look up the Home in the JNDI
    InitialContext ic = null;
    // First look for the JNDI context reference in the cache
    ic = (InitialContext) hashMap.get("ic");

    if(ic==null) {
    // If its not in the cache, create one and then store the reference
    ic = new InitialContext();
    hashMap.put("ic", ic);
    }

    ejbHome = (EJBHome) ic.lookup( jndiNameOfEjb );

    // After looking up, put it in the Hasttable for future reference calls
    if(ejbHome!=null) {
    hashMap.put( jndiNameOfEjb, ejbHome);
    }

    }

    return ejbHome;
        }
    }
  23. This article (http://www-106.ibm.com/developerworks/java/library/j-dcl.html?loc=j) states that the double-checked locking is a broken idiom.

    In what article does Peter state that the Singleton pattern is a broke 'idiom' ? I think Singleton is not an idiom, but rather a design pattern.

    Cheers
  24. Static Singleton Interface[ Go to top ]

    Just to clarify the problem with the idiom is not just the amount of components using your class (which 1100 seems a lot depending on what your doing), it is the traffic on the threads that are using your class.

    So if you have 1100 components talking to your class with about 2 users on the system you probably won't even see the issue with the double-check locking. But if you have about 1 million users on your system all accessing your site as you start up your app server instance then you would probably see the issue. You can probably get around the issue of double-check locking within a web app by simply calling the getInstance call within your servlet init method and having the app server invoke it before the users are able to use your servlet/context. (of course this would require configuration of your web.xml to have the init property be set for your servlet)
  25. Static Singleton Interface[ Go to top ]

    My personal opinion, there are some problems in doing like this.

    1. you can not have multiple instance.(Gary Bisaga already said so)
    2. it limits to be initialized when class is load.(Gene Chuang told me)
    3. it makes confusion if it has non-static member class as well, cause you have to keep in mind which call should use getInstance() and which need not. And if you do not have any non-static methods, ( so you can not synchronize the object but only the class), it is not quite wise to use non-static member variables. And if you do not have non-static member variables as well, it seams no use to instantiate such class.
    4. to solve the problem of 3, we need to envolope each non-static method with a static method ?!

    After look at it twice, I suspect that this class is really not quite cohesive. we actually have two classes, the first one is a normal singleton, the other one is a envolope class consists only static methods. The envolope class is for example:
    public class SingletonEnvo{
        public Object getField1(){
            return Singleton.getInstance().getField1();
        }
    }
    and I think the above works just as fine as your example.

    the envolope class has the value of
    1. make singleton method call more "clean"( avoid to call getInstance() for example )
    2. "cached your Singleton using a SoftReference or some other method for caching"

    the singleton class has the value of
    1. hide the initialization.
    2. control the number of instance of the class.
    3. and more
    these two classes are not coupling enough to deserve to be combined.
  26. Static Singleton Interface[ Go to top ]

    I made a mistake, the forth line "non-static member class" should be corrected as "non-static member method", sorry.
  27. Static Singleton Interface[ Go to top ]

    Great idea. That way you get the best of both worlds, and the client can pick either interface.

    Bob
  28. Static Singleton Interface[ Go to top ]

    Hey Bob,

    I would like to conclude the moral of the story:
    Singleton pattern is at its best when it provides following benifits:
    1) It hides the instance initialisation.
    2) It ensures single instance of an object, and which can later esily be made multipleton, if required.
    3) Can be easily extended by sub classes without causing problem to existing code.
    4) It allows lazy initialisation.

    Based on what you need, u can identify if your class need to be singleton, else if u want to sacrifice some benifits, you can be fine with static class.

    I would also like to add that most of the factory classes should be made singleton as long as they do not contain any read-write attribute.

    Do everybody agree with my statements?
  29. Static Singleton Interface[ Go to top ]

    I agree that it was a mistake to offer this as an alternative to the Singleton pattern.

    In retrospect, "Pluggable Booch Utility" would have been a much better title.

    This pattern provides for a simple, secure client utility interface while providing you implementation flexibility benefits similar to those that you get with a Singleton or Factory.

    Thanks for clarifying.
  30. Static Singleton Interface[ Go to top ]

    why in the world would you EVER extend the implementation of a singleton? why? ever?

    99% of the time you're taking static data (let's call the class Envrionment (instead of Singleton (which makes no sense...it's like calling something Factory (factory for what????)) when in the heck would you extend the implementation?

    if you want to use the class' services, call its methods (delegate), don't extend it, please.
  31. I agree here. Extending a Singleton is very dangerous and in my experience has led to hard to find and understand bugs.

    This is because static field are not inherited, but are class members. In the following implementation all subclasses will share the same instance with the original Singleton class and the first one to be initialized wins!

    class Singleton {
        protected static Singleton instance;
        public static Singleton getInstance() {
           if (instance == null) instance = new Singleton();
        }
        ...
    }
    class SubSingleton extends Singleton {
        public static Singleton getInstance() {
           if (instance == null) instance = new SubSingleton();
        }
        ...
    }
    ...
    Singleton ston = Singleton.getInstance();
    SubSingleton subSton = SubSingleton.getInstance();
    System.out.println("test=" + subSton instanceof SubSingleton);

    and the output is: test=false

    Therefore, I always make my Singleton implementations final.

  32. Static Singleton Interface[ Go to top ]

    Class and Instance are not the same Entity.

    Your Singleton implementation is not a purist OO aproach because the field "someField" is not a class field, is a instance field.
    If you need performance do the following:

    class Singleton {
        final public Singleton instance = new Singleton();

        private Singleton() {}
        public SomeField getSomeField() {
          ...
        }
    }


    And you can invoke this Singleton in the following way:

       Singleton.instance.getSomeField() ...

  33. Static Singleton Interface[ Go to top ]

    Based on what you are doing, there is no benefit to using the Singleton pattern. You've not taken advantage of the pattern. The last snippet you present could simply be written as:

    public class Singelton
    {
      private Singleton() {}

      private Object someField;

      public static Object getField()
      {
        return someField;
      }
    }

    There is no benefit to using a singleton as you have listed it: your methods are static anyway. One uses the singleton pattern to gain a more natural instance accessibility while guarenteeing a single instance.
  34. Static Singleton Interface[ Go to top ]

    I've used the Singleton pattern many times in the past, and the only benefit I get from using them would be during cases where I have a class that initializes itself in some special way upon loading, and that specific initializing remains in the class state and should not be changed by users of the class. Take a PropertyManager class, for example. This class has the responsibility to read physical property files and load them into java.util.Property objects that all get stores into a static hashtable. Of course, reading a property file should occur only once since property files dont change very often. Therefore, the manager can read all property files during a static initialization, then allow users of the class to gain access to the Property objects which represent the actual data in the files via a logical alias to the object. In this case, there is no need to force users of the class to continously create an instance of the manager to get access to the Property objects. So, you only need one instance of the manager, therefore, use a singleton.

    SAF
  35. Static Singleton Interface[ Go to top ]

    Hi I have a requirment:

    I need to have an in memory object i need to read and write. (Like an Hash table to add and delete records).

    I do not want to persist data in the database. What are my choices. Singleton is good for a read not for a write. what should i do?

    a) Singleton pattern: I can stick my memory object in the JNDI tree. This might be efficient if you have to &#8216;read&#8217; data but unreliable (as JNDI is a directory service for LOOK UP and not sophisticated like a RDMS for multi client writes) if you have instances of stateless session bean changing the same object
  36. Static Singleton Interface[ Go to top ]

    Hi I have a requirment:

    I need to have an in memory object i need to read and write. (Like an Hash table to add and delete records).

    I do not want to persist data in the database. What are my choices. Singleton is good for a read not for a write. Any suggestions?
  37. Static Singleton Interface[ Go to top ]

    Hi Bob

    I agree with you that getInstance() shouldn't be used by the singleton client but rather simply do Singleton.getField(). On the other hand I agree with Gene Chuang that there is no garantee that the JVM will initialize static members and this could be a problem on certain JVM implementation. So another variant could have a *private getInstance()* and look like this:

    public class Singleton {
      private static Singleton instance = new Singleton();
      private Object field;

      private Singleton() {
      }

      private static synchronized Singleton getInstance() {
        if (instance = null) instance = new Singleton();
        return instance;
      }

      public static synchronized Object getField() {
        return getInstance().field;
      }
    }

    What do you think?
    Regards
    Alain

    PS: thanks Christian for the hint!
  38. Static Singleton Interface[ Go to top ]

    Hi!

    I have some question regarding this static Singleton pattern:

    1. Is it thread safe to use the class loader to instantiate the 'private static instance Singleton = new Singleton();' vs using an unsychronized getInstance() 'lazy' method? My company is recommending this 'static Singleton' pattern for developing Singletons that are accessed by servlets.

    2 I thought the class loader MUST instantiate all static variables before they are referenced so what's the big deal of getting it to control initialization? Does the Sun JVM and/or IBM JVM do a bad job of handling this?

    3. For the unsynchronized 'lazy' getInstance() pattern as opposed to this pattern, I've read that 'double check locking' doesn't work in java??? Soooo, does that mean you trade-off performance and OO purity?

    4. What's the difference between this pattern and just declaring a class:

       class MySingleton {
          public static final ITarget S = new CTarger();
       }

    where:
       ITarget is an interface
       CTarget is a concrete implementation if ITarget whose members are immutable.

    ... it's less typing... even with modern IDE's and I see no particular difference between doing this and declaring/referenceing primitive type contstants.

      This would make the CTarget class extendable/pluggable and since people are saying 'this pattern isn't OO pure' why not go all the way with it?

  39. Static Singleton Interface[ Go to top ]

    I don't wanna argue if this is sync or not, why should this be that or not... just wanna say that by using static member methods to access your single instance you're revoking the access to "this" reference which might be useful for such things as logging.

    Ciao.
  40. Static Singleton Interface[ Go to top ]

       class MySingleton {
          public static final ITarget S = new CTarget();
       }

    where:
       ITarget is an interface
       CTarget is a concrete implementation if ITarget whose members are immutable.

    IF you want to do logging or add some other behaviour, couldn't you just implement another CTarget class to do this?

    Besides the obvious "it's not proper OO" reasons, are there any practical gotcha's of doing it this way?.

    Thanx for your input!
  41. Static Singleton Interface[ Go to top ]

    The only limitation with this is that you can not have controlled instantiation. Singletons are not only to make sure that there is only one instance, but also not to create even that "one instance" until you need it. With your implementaion you load the instance with JVM instance.