Showing posts from July 27, 2007

Java Singleton Pattern : Potential Problems and Solutions

The Java Singleton pattern belongs to the family of design patterns that governs the instantiation process. This design pattern suggests that at any time there can only be one instance of a Singleton (object) created by the JVM. You implement the pattern by creating a class with a method that creates a new instance of the class if one does not exist. If an instance of the class exists, it simply returns a reference to that object.How the Singleton pattern works:Here’s a typical example of Singleton:public class Singleton { private final static Singleton INSTANCE = new Singleton(); // Private constructor suppresses generation of // a (public) default constructor private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }The classic Singleton does not use direct instantiation of a static variable with declaration — it instantiates a static instance variable in the constructor without checking to see if it already exists:public class C…