Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Singleton Design Pattern in Java
Next article icon

Java Singleton Design Pattern Practices with Examples

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. 
In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. 
There are many ways this can be done in Java. All these ways differ in their implementation of the pattern, but in the end, they all achieve the same end result of a single instance. 
 

  1. Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference of an instance directly. 
    It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time.
     
JAVA
// Java code to create singleton class by  // Eager Initialization public class GFG  {   // public instance initialized when loading the class   private static final GFG instance = new GFG();    private GFG()   {     // private constructor   }   public static GFG getInstance(){         return instance;     } } 

  1. Pros:
    1. Very simple to implement.
    2. May lead to resource wastage. Because instance of class is created always, whether it is required or not.
    3. CPU time is also wasted in creation of instance if it is not required.
    4. Exception handling is not possible.
  2. Using static block: This is also a sub part of Eager initialization. The only difference is object is created in a static block so that we can have access on its creation, like exception handling. In this way also, object is created at the time of class loading. 
    It can be used when there is a chance of exceptions in creating object with eager initialization. 
     
JAVA
// Java code to create singleton class // Using Static block public class GFG  {   // public instance   public static GFG instance;    private GFG()    {     // private constructor   } static   {     // static block to initialize instance     instance = new GFG();   } } 

  1. Pros:
    1. Very simple to implement.
    2. No need to implement getInstance() method. Instance can be accessed directly.
    3. Exceptions can be handled in static block.
    4. May lead to resource wastage. Because instance of class is created always, whether it is required or not.
    5. CPU time is also wasted in creation of instance if it is not required.
  2. Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created. To make sure that class cannot be instantiated in any other way, constructor is made final. As object is created with in a method, it ensures that object will not be created until and unless it is required. Instance is kept private so that no one can access it directly. 
    It can be used in a single threaded environment because multiple threads can break singleton property as they can access get instance method simultaneously and create multiple objects. 
     
JAVA
//Java Code to create singleton class // With Lazy initialization public class GFG  {   // private instance, so that it can be   // accessed by only by getInstance() method   private static GFG instance;    private GFG()    {     // private constructor   }    //method to return instance of class   public static GFG getInstance()    {     if (instance == null)      {       // if instance is null, initialize       instance = new GFG();     }     return instance;   } } 

  1. Pros:
    1. Object is created only if it is needed. It may overcome wastage of resource and  CPU time.
    2. Exception handling is also possible in method.
    3. Every time a condition of null has to be checked.
    4. instance can’t be accessed directly.
    5. In multithreaded environment, it may break singleton property.
  2. Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously.
     
JAVA
// Java program to create Thread Safe // Singleton class public class GFG  {   // private instance, so that it can be   // accessed by only by getInstance() method   private static GFG instance;    private GFG()    {     // private constructor   }   //synchronized method to control simultaneous access   synchronized public static GFG getInstance()    {     if (instance == null)      {       // if instance is null, initialize       instance = new GFG();     }     return instance;   } } 

  1. Pros:
    1. Lazy initialization is possible.
    2. It is also thread safe.
    3. getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.
  2. Lazy initialization with Double check locking: In this mechanism, we overcome the overhead problem of synchronized code. In this method, getInstance is not synchronized but the block which creates instance is synchronized so that minimum number of threads have to wait and that’s only for first time.
     
JAVA
// Java code to explain double check locking public class GFG  {   // private instance, so that it can be   // accessed by only by getInstance() method   private static GFG instance;    private GFG()    {     // private constructor   }    public static GFG getInstance()   {     if (instance == null)      {       //synchronized block to remove overhead       synchronized (GFG.class)       {         if(instance==null)         {           // if instance is null, initialize           instance = new GFG();         }              }     }     return instance;   } } 

  1. Pros:
    1. Lazy initialization is possible.
    2. It is also thread safe.
    3. Performance overhead gets reduced because of synchronized keyword.
    4. First time, it can affect performance.
  2. Bill Pugh Singleton Implementation: Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton.
     
JAVA
// Java code for Bill Pugh Singleton Implementation public class GFG  {    private GFG()    {     // private constructor   }    // Inner class to provide instance of class   private static class BillPughSingleton   {     private static final GFG INSTANCE = new GFG();   }    public static GFG getInstance()    {     return BillPughSingleton.INSTANCE;   } } 

  1. When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class. Inner class is created only when getInstance() method is called. So it may seem like eager initialization but it is lazy initialization. 
    This is the most widely used approach as it doesn’t use synchronization.


 

When to use What


 

  1. Eager initialization is easy to implement but it may cause resource and CPU time wastage. Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class.
  2. By using Static block in Eager initialization we can provide exception handling and also can control over instance.
  3. Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. 
     
  4. Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages.




 



Next Article
Singleton Design Pattern in Java

V

Vishal Garg
Improve
Article Tags :
  • Design Pattern
  • Java
  • System Design
Practice Tags :
  • Java

Similar Reads

  • Singleton Design Pattern in Java
    Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system. Important Topics for Singleton Method in Java
    5 min read
  • Design Patterns: Understand The Importance With Real Life Examples
    Software Design Patterns... Software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. This is the definition written on Wikipedia for software design patterns...The above definition makes sense to you if you are an experienced
    8 min read
  • Open Closed Principle in Java with Examples
    In software development, the use of object-oriented design is crucial. It helps to write flexible, scalable, and reusable code. It is recommended that the developers follow SOLID principles when writing a code. One of the five SOLID principles is the open/closed principle. The principle states that
    9 min read
  • Singleton Method Design Pattern in Java
    In object-oriented programming, a Java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So, whatever modifications we d
    8 min read
  • Singleton Method Design Pattern
    The Singleton Method Design Pattern ensures a class has only one instance and provides a global access point to it. It’s ideal for scenarios requiring centralized control, like managing database connections or configuration settings. This article explores its principles, benefits, drawbacks, and bes
    11 min read
  • Pattern compile(String) method in Java with Examples
    The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.compile() method.Synta
    2 min read
  • Strategy Design Pattern in Java
    The Strategy Design Pattern in Java defines a family of algorithms, encapsulates each one, and makes them interchangeable, allowing clients to switch algorithms dynamically without altering the code structure. Important Topics for Strategy Design Pattern in Java What is the Strategy Design Pattern i
    13 min read
  • Single Responsibility Principle in Java with Examples
    SOLID is an acronym used to refer to a group of five important principles followed in software development. This principle is an acronym of the five principles which are given below… Single Responsibility Principle (SRP)Open/Closed PrincipleLiskov’s Substitution Principle (LSP)Interface Segregation
    7 min read
  • Top 30 Java Design Patterns Interview Question
    If you want to be a ​software developer or ​engineer, you need to know about design patterns. They're like solutions to common problems in software design. In job interviews, employers ask about design patterns to see if you know what you're doing. So, it's important to be ready for those questions.
    15+ min read
  • Prototype Design Pattern in Java
    The Prototype Design Pattern in Java is a creational pattern that enables the creation of new objects by copying an existing object. Prototype allows us to hide the complexity of making new instances from the client. The concept is to copy an existing object rather than create a new instance from sc
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences