Singleton Pattern

The Objective of the pattern is,at any given time there can be only one instance of a class.

A singleton pattern can be used to create a Connection Pool. We can have connection object as singleton to avoid wastage of

Steps to create a singleton pattern,

  1. We need to have default constructor of the class as private, which prevents instantiation of the object by other classes.

  2. Define a static method that returns singleton object, If object doesn't exists new object is returned otherwise existing
    object would be returned.

  3. To avoid the object being cloned, override the clone method of the Object class.

  4. If a application is going to be Multithreaded one then there can be chances wherein two therads at the sametime can access the static method which may create more than one instance of the singleton class. To avoid the above scenario we need to have this static method as synchronized.

class Singleton {
private static Singleton singletonObject;
private Singleton{

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

public Object clone()throws CloneNotSupportedException{
throw new CloneNotSupportedException();

public class SingletonObjectDemo{
public static void main(String args[]){
//Singleton obj = new Singleton(); Would cause Compilation error.
//create the Singleton Object..
Singleton obj = Singleton.getInstance();


No comments:

Tired of seeing that 500 Bad gateway error while deploying a Springboot application in AWS...?

By default, Spring Boot applications will listen on port 8080. Elastic Beanstalk assumes that the application will listen on port 5000. Th...