Singleton design pattern in java - Java @ Desk

Tuesday, June 4, 2013

Singleton design pattern in java

As the name suggests, Singleton patters allows only single instance of particular class throughout the application.

Why to create a Singleton class in an application?

Answer: Say for instance, an application wants to load a property class which contains a set of properties, and this property file is being used throughout the application. So a better way is to load that property file once and use it throughout.

The basic example of a singleton design pattern is shown below:

public class SingletonPattern {

// Make the constructor private so that it cannot be 
//instantiated outside the class
    private SingletonPattern() {

    // Variable for SingletonPattern class
    private static SingletonPattern singletonPattern;

    // Method to get the instance of SingletonPattern class
    public static SingletonPattern getSingletonPatternObject() {
        if (singletonPattern == null) {
            singletonPattern = new SingletonPattern();
        return singletonPattern;
Usage of singleton patterns:
Typically singletons are used for global configuration. The simplest example would be LogManager
The other example is RunTime class
Database connections
Configuration or property files

Issues in this implementation:
1) It could happen that SingletonPattern.getSingletonPatternObject() call may occur from 2 different places in an application at the same time and 2 objects get created which will violate the principal of the pattern

2) Consider the code
SingletonPattern clonedSingletonPattern = (SingletonPattern) obj.clone();
This code will create the copy of the singleton object which again violates the design patters implementation

Click Singleton Pattern Java With Double Locking and Without Cloning for complete version of Singleton Design Pattern

References for design patterns
Improved version of Singleton pattern

1 comment:

  1. one blog explained the Singleton Design pattern good please go through this blog