Java : singleton with example

A singleton is a class that can be instantiated once, and only once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM). Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running.
public class SingletonObject {
   //marked as private so that class can't be directly instantiated
   private SingletonObject() {
      // no code req'd
   }

   //add synchronized keyword to prevent thread making a new copy
   public static synchronized SingletonObject getSingletonObject() {
      if (ref == null) {
         // it's ok, we can call this constructor
         ref = new SingletonObject();
      }
      return ref;
   }

   //overwrite default clone method so that this class can't be cloned
   public Object clone()
   throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
      // that'll teach 'em
   }

   private static SingletonObject ref;
}

reference : http://www.javacoffeebreak.com/articles/designpatterns/index.html

2 comments:

  1. Nice post , just to add
    While writing Singleton class we need to consider many points e.g.
    1) Lazy initialization
    2) Early initialization
    3) Serialization
    4) Many ClassLoaders


    to tackle all above problem best way is to use JAVA 5 Enum functionality and write Singleton using Enum like below.
    public enum Singleton {
    INSTANCE;

    public static void hi(){
    System.out.println("Hi");
    }
    }

    Thanks
    Javin
    Why String is immutable in Java

    ReplyDelete
  2. It's been a while I didn't look at this blog, anyway thanks Javin for pointing this out. Have a nice day :)

    ReplyDelete