Java Singleton


It may be necessary, sometimes for performance reasons, to create a single object for the whole class. Programmer may create a number of objects in the code, but internally only one object is created. This is transparent (not known) to the Programmer. Java Singleton is a design pattern. A design pattern is a solution given by expert people on the subject matter to a frequently occurring problem. Design patterns are available in every field like Civil, Mechanical and Accounts etc.

Singleton pattern is useful when the Developer would like to create only one object for the whole class; even if created a number of objects, internally the code creates only one. Finally to say, for Singleton class only one object is created. This is the sense and meaning of Singleton.

Merits or Uses Java Singleton
  1. Java Singleton is useful when the code can manage all the operations with one object. Creating less objects uses less space and less time and thereby performance increases.
  2. When the values are required only once in the code to populate the instance variables that can be used number of times. Through Singleton, database access is done only once, values are retrieved and fed to variables or DS elements.
  3. To control the number of objects creation in the code and to create only one all through the life.
  4. When only one object exists, the fields can be static also to control database access, open socket and to open file handles etc.
  5. Java Singleton is useful when one object is required in multithreaded environment like ActionServlet controller in Struts 1.0.
  6. In realtme applications, the JRE (Java Runtime Environment) is a Singleton object.
Demerits of Java Singleton
  1. If not necessary actually, creation of Java Singleton keeps unnecessary restrictions on global runtime code execution environment.
Internal mechanism of Java Singleton Object Creation

Generally in usual coding, object is created with a constructor call. But in Java Singleton, the object is created through a method call. The method when first time called creates object and returns. When called second time, the reference of the earlier object is returned but new object is not created. To achieve this, constructor is declared private so that outside classes call the constructor and create the objects (like public methods and private variables concept). Some people make protected constructors so that Testers are allowed to check.

Programmer should take precautions in multithreaded environment not allow the Developers to clone the Single object something by doing synchronization.

Steps of creating Java Singleton Object

Steps can be narrowed to four.

  1. Declare the constructor private so that it cannot be called directly from outside the code
  2. Write a method creating and returning the Java Singleton object
  3. Synchronize the method to make better thread-safe
  4. To prevent cloning of Singleton object, override the Object class clone() method
Learn the technique of Java Singleton object creation in this Employee Example where only one object is created inspite of number of calls.
public class Employee                 
{                                     // private variables so that not accessed by outside code
  private int salary;                 // assigned with default 0
  private static Employee emp;        // assigned with default null

  private Employee()                  // private constructor; 1st step of the above four
  {     
     // not required any code here
  }
  public static synchronized Employee getPlease() // 2nd and 3rd steps of the above four
  {                                               // public method allowed to access from outside the code
    if(emp == null)                               // this is important statement of all the code
    {
      emp = new Employee();  
    }
    return emp;
  }

  public Object clone() throws CloneNotSupportedException  // override the clone() method;
  {                                                        // 4th step of the above four
     throw new CloneNotSupportedException("Cloning is not permitted on Singleton Please");
  }

  public static void main(String args[])
  {
      Employee emp1 = getPlease();
      Employee emp2 = getPlease();

      emp1.salary = 7000;
      emp2.salary = 8000;
      System.out.println("emp1 Salary when emp2 changes: " + emp1.salary);   // 8000

      emp1.salary = 9000;
      System.out.println("emp2 Salary when emp1 changes: " + emp2.salary);   // 9000

      System.out.println("\nemp1 hash code: " + emp1.hashCode());            // both hascodes prints the same
      System.out.println("emp2 hash code: " + emp2.hashCode());     
  }
}

Java SingletonOutput Screenshot on Java Singleton

Code is almost self-explanatory with all the comments. I discuss which required.

  public static synchronized Employee getPlease() 
  {                                   
    if(emp == null)                   
    {
      emp = new Employee();  
    }
    return emp;
  }

getPlease() is made pubic to that the code is permitted to be called by other classes from any package. Made static to allow to be called from main() without object need.an object. First time when called, the method creates an Employee object as object is null (as no object exists). When called second time, the object is not null (as object exists), if statement is not executed, the same emp object created earlier is returned. This is the internal mechanism a Developer should adopt.

Employee emp1 = getPlease();
Employee emp2 = getPlease();

emp1 and emp2 objects are created by calling getPlease() method. But both refer the same emp object. For outsiders, they look different. But actually only one exists. This is transparent (not known) to outsiders.

The proof is when emp2 changes emp1 gets affected and vice versa.

Observe the Screenshot, their hash codes are same.

clone() method is more discussed at Cloning Duplicate Object Marker Interface.

JDK 1.5 gives simple way to create Java Singleton.
  1. Write Enum object of JDK 1.5 which implicitly thread-safe (no necessary for synchronization)
  2. Enum Singleton is capable to do Serialization implicitly
Uses of Java Singleton
  1. In a class if no variables exist to maintain state between objects.
  2. If all fields or variables are final. That is, to have read-only state.( all attributes are final)

1. View All for Java Differences on 80 Topics
2. View All for Java Conversions on 30 Topics

Leave a Comment

Your email address will not be published. Required fields are marked *