$show=/label

Java Singleton Design Pattern To Create Single Instance with Best Practices

SHARE:

A quick guide to how to implement a Singleton design pattern in java. Java Singleton pattern always returns only one object even if you call the method multiple times. See how to interview questions are asked on the singleton.

1. Introduction


In this article, We'll learn what is singleton pattern in java and how to implement it. You will learn various ways to create singleton objects. This is the only design pattern that is used by every application in the software industry and also used extensively in java api such as Spring, apache or spark, etc. A question from the design pattern is a must in the interview and many questions come from this topic. This is my favorite interview question that i ask for software developers. This question will check to understand of many areas of core java such as private access modifier, static members, cloning, multithreading, deep cloning, serialization and deserialization and reflection api.


In this post, You will learn the frequently asked question on the singleton design pattern. If you are preparing for interviews, this will give you a clear picture of the singleton pattern.


2. Singleton Design Pattern Rules


Sington means always one object should exist in the entire life of an application at any time. If a class produces two objects or more then it is not a singleton pattern.

Let us understand the rules for the singleton pattern.

  • First, need to make constructor private so that object can not be created from any other class.
  • Create, Static field with referencing the same class object.
  • Create a static method to get the singleton instance. This method will be invoked by other classes to get the singleton instance.


3. Singleton Design Pattern Creation

Creating a singleton class.

package com.java.w3schools.blog.java.program.to.desingpatterns;

public class SingletonPattern {

 // private static field.
 private static SingletonPattern instance;

 // private constructor
 private SingletonPattern() {

 }

 public static SingletonPattern getInstance() {
  if (instance == null) {
   instance = new SingletonPattern();
  }

  return instance;
 }

}

4. Singleton Design Pattern Verification


Created 3 singleton class objects in the below program. Printed all 3 objects and hascodes as well. 


package com.java.w3schools.blog.java.program.to.desingpatterns;

public class SingletonPatternMain {

 public static void main(String[] args) {

  SingletonPattern object1 = SingletonPattern.getInstance();

  SingletonPattern object2 = SingletonPattern.getInstance();
  
  SingletonPattern object3 = SingletonPattern.getInstance();
  
  System.out.println("object 1 " + object1);
  System.out.println("object 2 " + object2);
  System.out.println("object 3 " + object3);

  System.out.println("object 1 hashCode " + object1.hashCode());
  System.out.println("object 2 hashCode " + object2.hashCode());
  System.out.println("object 3 hashCode " + object3.hashCode());
 }

}

Output:

Observe the output and all objects are having same memory address and hascodes. So, It is creating always single objects.

object 1 com.java.w3schools.blog.java.program.to.desingpatterns.SingletonPattern@4b1210ee
object 2 com.java.w3schools.blog.java.program.to.desingpatterns.SingletonPattern@4b1210ee
object 3 com.java.w3schools.blog.java.program.to.desingpatterns.SingletonPattern@4b1210ee
object 1 hashCode 1259475182
object 2 hashCode 1259475182
object 3 hashCode 1259475182

5. Singleton Design Pattern In Multiple threads


If the above code is used in concurrent applications there might be a chance of creating multiple objects. To avoid duplicate objects creation, object creation logic should be sourrounded by some special monitor. This object creation logic is called as critical section and this should be synchronized.

5.1 Synchronizing Critical Section


public static SingletonPattern getInstance() {


  if (instance == null) {
  
   synchronized (SingletonPattern.class) {
    instance = new SingletonPattern();
   }
  }

  return instance;
 }
The above code is called as single locking beacuse only once if(instance == null) is checked.

5.2 Double Checked Locking


The above code is still having the chances for multiple objects creation. To prevent this from multiple threads, double checking logic should be used here.

 // double locking pattern.
 public static SingletonPattern getInstance() {
  if (instance == null) {
   synchronized (SingletonPattern.class) {
    if (instance == null) {
     instance = new SingletonPattern();
    }
   }

  }

  return instance;
 }

6. Creating Singleton with ENUM


Now, let us jump into another interesting way of creating singleton with Enum. This approach is more safe from cloning, serialzation and multiple threads.

public enum SingletonEnum {

 INSTANCE("enum singleton");

 private String state;

 private SingletonEnum(String state) {
        this.state = state;
    }

 public SingletonEnum getInstance() {
  return INSTANCE;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

}

Verification with Enum:


public enum SingletonEnum {

 INSTANCE("enum singleton");

 private String state;

 private SingletonEnum(String state) {
        this.state = state;
    }

 public SingletonEnum getInstance() {
  return INSTANCE;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

}

Output:

enum singleton instance : enum singleton
enum singleton instance : enum singleton
enum singleton instance : enum singleton

7. Singleton Breaking With Cloning


This is a interview question. If Singleton class implements Clonable interface and implemnted clone() then it returns new object each time clone() method is called.

package com.java.w3schools.blog.java.program.to.desingpatterns;

public class SingletonPattern implements Cloneable{

 // common doublechecking logic or normal singel ton code.
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  // TODO Auto-generated method stub
  return super.clone();
 }

}

Let us check the hashcode's of cloned objects.


SingletonPattern object4 = SingletonPattern.getInstance();
System.out.println("Object 4 hashcode : " + object4.hashCode());

SingletonPattern object5 = (SingletonPattern) object4.clone();
System.out.println("Object 5 hashcode : " + object5.hashCode());

SingletonPattern object6 = (SingletonPattern) object4.clone();
System.out.println("Object 6 hashcode : " + object6.hashCode());

Output:

Object 4 hashcode : 1259475182
Object 5 hashcode : 1300109446
Object 6 hashcode : 1020371697

How to prevent singleton from cloning?


Answer 1: Return the same singleton instance from the clone method.

@Override
protected Object clone() throws CloneNotSupportedException {
 // TODO Auto-generated method stub
 return instance;
}

Answer 2: Throw exception saying clonenotsupportexception.

@Override
protected Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException("Clone not supported for SingletonPattern class");
}

Note: But recommended is not to implement the clonable interface in singleton pattern.

8. Singleton Breaking With Deep Cloning or serialization


How do you prevent singleton for creating another new instance from serialization?


This is a great interview question but you should have deep understand on serialization. During the serialization, readObject() method is used to creat the object and return a new instance everytime with readResolve() method.  To prevent creating new object, just need to return the singleton instance from readResolve() method.

If you use Enum which is taken care all of these by JVM.


9. Sington Breaking With Reflection API


How to prevent singleton for creating another object from reflection api?

By using reflection api, We can change the constructor visibility to the public from private.

SingletonPattern object7 = SingletonPattern.getInstance();
System.out.println("Object 7 hashcode : " + object4.hashCode());

Constructor constructor = SingletonPattern.class.getDeclaredConstructor();
constructor.setAccessible(true);
SingletonPattern pattern = constructor.newInstance();
System.out.println("singeleton new object through reflection api : " + pattern.hashCode());

Output:

Object 4 hashcode : 1259475182
singeleton new object through reflection api : 1300109446

This can be avoided by throwing exception from constructor if the singleton instance is not null.

 // private constructor
 private SingletonPattern() {

  if (instance != null) {
   throw new RuntimeException("You can create new object.");
  }

 }

10. Java API Singleton Classes


What are the Java built-in Singleton classes in Java API?


Runtime, Toolkit and Desktop classes are singleton classes.

Java.lang.Runtime with getRuntime()
Java.awt.Toolkit with getDefaultToolkit() 
Java.awt.Desktop with getDesktop()

11. Conclusion


In this article, we've seen what is singleton pattern and how to implement it? Frequently asked interview questions.

In conclusion, all examples are shown in this article are in GitHub

[lock]
GitHub Cod
[/lock]

Java Singleton Design Pattern 

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Singleton Design Pattern To Create Single Instance with Best Practices
Java Singleton Design Pattern To Create Single Instance with Best Practices
A quick guide to how to implement a Singleton design pattern in java. Java Singleton pattern always returns only one object even if you call the method multiple times. See how to interview questions are asked on the singleton.
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/java-singleton.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/java-singleton.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content