Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 23 November, 2022

5.21K+ views
8 min read

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.

Read: Java Architecture & Components Explained

Initialisation

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.

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

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.

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

Conclusion

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.

Frequently Asked Questions (FAQs)

1. What 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.

2. What 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.

3. What 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.

RELATED PROGRAMS