Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconHow to Make Singleton in Java? Types of Initialization, Comparison & Points To Remember

How to Make Singleton in Java? Types of Initialization, Comparison & Points To Remember

Last updated:
6th Oct, 2020
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
How to Make Singleton in Java? Types of Initialization, Comparison & Points To Remember

A singleton class in Java is defined as that class that has only one object, i.e. only one instance of the class. The restricting of the instance to only one per class helps in coding particular programs that require only one instance of the class. The only instance of a singleton class is given a global point of access.

Singleton class is one of the important design patterns in Java programming. Singleton classes help in limiting resources and optimising them; it is used a lot in database connections or sockets. There are implementation syntaxes for singleton class, and a good developer must know about it. Let us see the implementation of the singleton class in Java. 

Check out our free courses to get an edge over the competition 

Learn Software engineer programs online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Ads of upGrad blog

Read: Java Architecture & Components Explained


The initialisation of a singleton in Java is done through a private constructor. Private constructors help in other classes not being able to create the same instance as of your singleton class. There are five types of initialisation of singleton class in Java which is listed below:

1. Eager Initialisation

 A public method commonly named as getInstance() is created. This method will help in providing only one entry point for creating an instance of the class, thus making it a singleton class. The instance of the class in eager initialisation is created at the time of class loading.

This type of initialisation technique creates the instance of the class automatically, even if the user is not using it. This may cause memory concerns & unnecessary length in code. To counter the memory leak problem, let us see another type of initialisation technique for a singleton class in Java.

Explore Our Software Development Free Courses

Check out upGrad’s Java Bootcamp 

2. Lazy Initialisation

The instance of the class is initialised in the method getInstance () itself in lazy initialisation. The method in lazy initialisation will check whether the instance of the class is created or not and if it is not created, then only it creates an instance, thus solving the memory leak problem.

The method one creates in lazy initialisation is static and has a return type object. The singleton instance in lazy initialisation will not be created until the getInstance() method is called for the first time.

3. Lazy Initialisation with Double Lock Method

This method is used at the time of more than one thread. If we are using two threads in the program, and both of them can be accessed via ‘if’ statement in starting when the instance is null, it will create a situation of conflict & you may find errors.

This problem is solved by the Double Lock Method in which only one thread enters at a time in the synchronised block for the initialisation of the instance while the other thread is blocked. When the first thread exits the synchronised block, then only the second thread enters & creates another instance. By default, the second thread does not check whether the instance is non-null or not.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

4. Lazy Load Method

Nested inner class is created in this method and works on principles of JLS (Java Language Specifications). There would be no static data members in the class; JVM will not create an instance of the class. The instance would be only created on demand when we invoke the getInstance() method.

You do not need to synchronise the method for initialisation & loading as this method helps in automatic synchronisation of all invocations of getting Instance().

5. Enums Method

Multiple instances of a singleton class can be still created by serialisation & reflection in the above methods. In the case of making a strict singleton class, this method can be used. Enums fields are used in this method which is a constant and runs at compile-time only.

An Enum is the instance of the Enum type and will be constructed only when the Enum type is invoked/called for the first time in the code. This method restricts the cloning of instance and makes a perfect singleton class.

Also Read: Top 12 Pattern Programs in Java You Should Checkout Today

Explore our Popular Software Engineering Courses

Serialisation & Reflection

Serialisation helps in the transportation of Java objects from one JVM (Java Virtual Machine) to another. Serialisation is one of the methods used for creating multiple instances of a class. Serialisation converts the object into a byte stream, and then the transfer is done.

The byte stream helps in recreating the object in some other JVM using the deserialization process. It helps multiple systems to communicate & share objects among them. It helps in cross JVM synchronisation as the objects will work in different JVMs.

Reflection is also a method of cloning objects in Java. Reflection is an API that helps us in knowing the class of any unknown object & methods of that particular class which can be accessed via the object. Reflection is widely used by programmers to modify the behaviour of classes & methods at run time.

The three major commands used in reflection are getClass() to know the class to which the object belongs, getConstructors() to get the public constructors of the class of the object, getMethods() to know the public methods of the class under observation.

In-Demand Software Development Skills

Normal Class Vs Singleton Class

A standard class in Java uses constructors to initialise itself, whereas we use the getInstance() method to initialise a singleton class. We can also use the same class & method name. We create an object first for normal classes, and then we use its methods & properties.

In contrast, in a singleton class, we create an instance using the static property of the class, and at any point throughout the code, that particular class will return only a single instance.

Besides many advantages of singleton classes, there are some loopholes too like singleton classes tamper unit testing methods if the objects & methods are tightly coupled. You will have to dedicate a fully functional class to a singleton in that case.

Hidden dependencies are also created by singleton class sometimes, as the reference of the singleton class is passed to other methods and it is not fully transparent thus making it challenging for coders/developers to keep track of the methods & classes. One should keep these shortcomings in mind before creating a singleton pattern and should try to minimise it.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?


Points to Make a Perfect Singleton Class

1. The points that should be focused to make a perfect singleton class are as follows:

2. If you are creating multiple threads in a singleton class, then make sure that all the threads should not initialise the singleton class at the same time. One should try to make thread-safe singleton classes.

3. Make your singleton class reflection proof, via changing the constructor visibility to the public at the run time & making sure there is only one instance of any particular singleton class.

4. If there are multiple threads, you can use a volatile modifier that prevents a thread from looking at the initialised state of other threads. A volatile modifier works on the happens-before relationship in which the write happens in a thread before any other thread can read it.

Must Read: Interesting Java Project Ideas for Beginners

Ads of upGrad blog

Read our Popular Articles related to Software Development


Singleton classes are used to make customised connections to the database or any program in which you want to control the methods & instances of the class. 

If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full stack development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development- Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.


Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is the basic idea behind Java?

Java, like C++, is a case-sensitive language of programming. It is a structure for Object-Oriented Programming (OOP) that uses classes. Java technique is being used to create applets as well as applications as well as it increases development speed and code portability. A software development project's five primary workflows are as follows: capturing requirements, analysis, layout, application, and testing. It even keeps local file system classes in a different namespace and prevents the execution of programs whose binary has been altered illegally.

2What are the uses of Java?

Java is an easy-to-learn programming language that lets you write code once and then operate it on almost every software device. It is platform-independent, and some programmes are written on the machines that can be done on one another. It is intended for the development of object-oriented programming language as well as multicore processing language with specific hardware. Since it is network-centric, it was designed for the distributed world of the Internet and to facilitate distributed computing. It is a simple language that lacks advanced structures such as pointers, operator overloading, multiple inheritance, and episodic memory allocation.

3What is the history of Java?

The past of Java is fascinating. Java was originally intended for interactive television, but the technology was too advanced for the electronic broadcast industry at the time. Java's history begins with the Green Team. Members of the Java team initiated this project to create a language for electronic devices such as predefined boxes, televisions, and so on. It was, however, better suited for web programming. Netscape later incorporated Java technology. It was designed keeping in mind the principles of simplicity, robustness, portability, security, concurrency, and dynamicity. Plus, it is architecture-neutral too.

Explore Free Courses

Suggested Blogs

35 Must Know Agile Methodology Interview Questions & Answers: Ultimate Guide 2023
Attending an agile interview and wondering what are all the questions and discussions you will go through? Before attending an agile testing interview
Read More

by Arjun Mathur

20 Nov 2023

DevOps Engineer Salary in India in 2023 [For Freshers & Experienced]
Wondering what is the range of DevOps Salary in India? In the last few years, DevOps has evolved from being just a “buzzword” to a mainstream practic
Read More

by upGrad

07 Nov 2023

What Is AWS Route 53 and How Does It Work?
Managing domain names and directing traffic efficiently is pivotal in the intricate web of cloud computing and web hosting. Enter AWS Route 53, Amazon
Read More

by Pavan Vadapalli

29 Sep 2023

Agile vs Scrum: Difference Between Agile and Scrum
Keeping up with the fast-paced nature of project development fueled by technological progress is challenging, to say the least. To function efficientl
Read More

by Pavan Vadapalli

28 Sep 2023

What Is Azure Active Directory? A Complete Guide
In the ever-evolving landscape of cloud computing, Azure Active Directory or Azure AD has emerged as a cornerstone in identity and access management.
Read More

by Pavan Vadapalli

28 Sep 2023

Difference Between Product Backlog and Sprint Backlog: A Quick Guide
Agile is a highly effective project management methodology, but its efficiency relies on the team’s collective understanding of key concepts, su
Read More

by Pavan Vadapalli

28 Sep 2023

Agile Manifesto Explained: Understanding Agile Values
Manifestos are formal declarations of principles or beliefs that guide movements or ideologies. The impact of the Agile Manifesto principles has exten
Read More

by Pavan Vadapalli

28 Sep 2023

Top 22 Best Agile Project Management Tools in 2023
The recent years have seen a surge in using the best Agile management tools and techniques, especially in software development. Breaking down projects
Read More

by Pavan Vadapalli

27 Sep 2023

Scrum Master Roles and Responsibilities: Everything You Should Know
In today’s fast-paced business environment, organisations constantly seek ways to enhance their productivity, collaboration, and product quality
Read More

by Pavan Vadapalli

27 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
footer sticky close icon