Singleton pattern in Java

Singleton Pattern

Singleton pattern ensures that only one instance of a class is created in the JVM. Once initialized, no more instances of that class can be created and previously created instance should be used across JVM. 

One thing to note – Even if there are multiple class loaders within a JVM, object instance should be same and shared by all. Otherwise it can defeat the whole purpose of singleton or single instance within a JVM.

Different ways of implementing singleton 

Before we get into different way of implementing Singleton, we need to understand how single instance of a class is enforced. First of all constructor should be private so that instance can’t be created using new operator outside of the class. After constructor is made private, singleton pattern can be implemented using following ways – 

1. Static method providing the instance using lazy creation when instance is required

This is the simplest of the implementation where instance is created when first requested by the caller. Whenever the static method is called, it first checks if the instance variable stored at the class level is null or not. In case it’s null, instance is created, stored at the class level and returned to the caller. Any caller to this static method after that gets the instance created in the first call. 

Leave a Reply

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