Java Singleton

Java Singleton is most important feature to understand.

Singleton is a design pattern where a class can have only one instance per application.

Logging, driver objects, caching, etc. are some of the examples of Singleton design pattern.

Singleton class will follow below three rules most of the time:

  1. it will always have a private default constructor which will never allow to create an instance outside of singleton class.
  2. static variable to assign an instance.
  3. static method to access Singleton class instance outside or singleton class.

Note: Singleton class will always return same instance of class.

There are two ways to create singleton instance:

Eager loading is to create an instance at the time of class load.

Lazy loading is to create an instance at the time when it is required.

Eager Loading

Follow below inline steps to create eager loading singleton class instance.

  1. Creation of static instance variable at line number 6 will get execute at compile or load time.
  2. Declare default constructor as private which will help us for not to create an instance outside of Singleton class.
  3. Now, for accessing an instance we require a static method as both instance variable and constructor is private.
  4. Return private instance variable created at line number 6 as part of static method.

OUTPUT
true

Output is true as this class is singleton and will always return same instance.

Lazy Loading

Follow below inline 4 steps to create lazy loading singleton class instance.

  1. Create static object of Connection class.
  2. Declare default constructor as private which will help us for not to create an instance outside of Singleton class.
  3. Now, create static method to create and return of an instance of class.
  4. Return private instance variable created at line number 6 as part of static method.

OUTPUT
true

Output is true as this class is singleton and will always return same instance.

Thread Safe Singleton class

In case of thread safe singleton class, only one thread can access singleton class instance at the same time.

Addition of synchronized keyword in static getInstance() method will convert above lazy loading singleton class to Synchronize or thread safe singleton class as shown below highlighted red in color.

OUTPUT
true

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan