Skip to content

  • Home
  • Core Java
    • Write Your Own Immutable Class In Java
    • Write Your Own Singleton Class In java
    • Java Concurrent Package
    • Java Stream Revisited
    • Print odd and even numbers using thread
    • SOLID principles
    • Comparable Vs Comparator
    • Sort HashMap/TreeMap based on value
    • Deep and Shallow Copy in Java with examples
    • Find the frequency of each character in a String
    • How to avoid duplicate Employee objects in HashSet ?
  • Spring
    • Loose Coupling & Dependency Injection
    • Bean Scope
    • Spring Bean Lifecycle
    • IoC Container Vs Application Context Vs Bean Factory
    • @Component Vs @Service @Repository Vs @Controller
    • How to read properties file in Spring
    • Spring AOP (Aspect Oriented Programming)
    • @Component Vs @Bean in Spring
    • Exception Handling in SpringBoot
    • XML configuration Vs Annotations configuration in Spring
    • Spring Data JPA
    • Spring Data REST
  • Spring Security
    • Spring Security with Form, Basic and JWT
    • Security Configuration in Spring Boot Apps
    • Security Protocols & Frameworks
    • Okta OAuth 2.0 SSO with Springboot
    • Spring Boot 2.x Security using Username Password
    • Spring Boot 2.x Security using JWT
    • Spring Boot 3.x Security using Username Password
    • Spring Boot 3.x Security using JWT
  • Microservices
    • Spring Cloud Config (Server & Client)
    • Spring Boot Microservices Tutorial (Part 1 of 2)
    • Spring Boot Microservices Tutorial (Part 2 of 2)
    • Circuit Breaker – Resilience4j
    • The Twelve-Factor App Principles
  • Event Driven Microservices
    • What is Event Driven Microservice ?
    • What is Saga Design Pattern ?
    • What is CQRS Design Pattern ?
  • Spring AI
    • ChatGPT API + SpringBoot Integration
  • Hibernate & JPA
    • JPA vs JDBC
    • CRUD Example Using Spring Boot JPA + H2 + Gradle
    • MongoDB Atlas With Spring Boot Example
    • Transaction Management
    • Relationships in JPA & Hibernate
    • Hibernate First & Second Level Cache
    • Spring Boot Flyway Postgres
  • DevOps
    • What is Devops ?
    • Docker
    • Kubernetes (K8S)
    • Jenkins
    • Infrastructure As Code
  • Functional Programming
    • Functional Programming Vs Structured Programming
    • Java 8 Programs For Interview
    • Predicate, Function, Consumer and Supplier in Java 8
    • Sort a List having Employee objects using Java 8
    • Find Employee from List using Java 8
  • AWS
    • AWS S3
    • AWS EC2
    • EC2 Solutions Architecting
    • How to create an EC2 instance ?
    • How to connect to AWS EC2 instance ?
    • Deploy application to AWS
    • AWS Lambda Java Tutorial
    • Spring Cloud Functions
    • How to Start/Stop AWS ECS automatically using Java Spring?
    • Container Solution in AWS
    • AWS SQS, SNS, MQ and Kinesis
    • Databases in AWS
    • AWS VPC: Peering, Endpoint, VPN, Gateways- Internet, NAT, DX
    • Machine Learning in AWS
    • Storage Solutions in AWS
    • AWS ASG (Auto Scaling Group)
  • AWS Certifications
    • SAA-C03
      • Design Cost-Optimized Architectures
    • AWS Certified Solution Architect-Associate
      • Question 1
  • Kafka
    • Apache Kafka
    • Kafka Producer & Consumer Example Using Spring boot & Conduktor
  • Angular
    • Angular Tutorial – Part 1
    • Angular Tutorial – Part 2
  • Miscellaneous
    • How to add a project to Git/GitHub/GitLab
    • How to Clone a project from Git/GitLab using Git Bash
    • How to query Oracle tables based on some date ?
    • How to highlight text in WordPress ?
    • How to add Page Jumps in WordPress page ?
  • Interview Preparation
    • Core java interview questions
    • Java Threads Interview Questions
  • Contact Me
  • Toggle search form

Write Your Own Singleton Class In java

Singleton class is a class which will create and refer the same single object, no matter how many time you instantiate an object out of it.
Below are the steps you can follow to create the same:

  1. Have a private constructor to prevent Singleton object instantiation from outside of the class.
  2. Have a private, volatile and static instance inside the class.
  3. Add no setter methods so that no one can change the value of the instance.
  4. Have a static method to return the instance value.
  5. Inside the above static method use double check locking to assign the value to it.
class MySingleton{
	
	private volatile static MySingleton instance;
	private MySingleton() {
		
	}
	
	public static MySingleton getMySingletonObject() {
		
		if(instance == null) {
			synchronized(MySingleton.class) {
				if(instance == null) {
					instance = new MySingleton();
				}
			}
		}
		return instance;
	}	
}

Lets test whether our singleton class is really working. How to check that ? We know if 2 objects are same object then their hashcode value should be same.
From any client class:

public class Manager {	
	public static void main(String[] args) {
		MySingleton instance1=MySingleton.getMySingletonObject();
		MySingleton instance2=MySingleton.getMySingletonObject();
		
		System.out.println("Hashcode of instance1: "+ instance1.hashCode());
		System.out.println("Hashcode of instance2: "+ instance2.hashCode());
	}
}

The output:

Hashcode of instance1: 366712642
Hashcode of instance2: 366712642

How to make singleton class reflection proof ?

In the below code we have taken help from reflection to break the singleton pattern:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Manager {	
	public static void main(String[] args) {
		MySingleton instance1=MySingleton.getMySingletonObject();
		MySingleton instance2=null;
		
        try {
            Class<MySingleton> clazz = MySingleton.class;
            Constructor<MySingleton> cons = clazz.getDeclaredConstructor();
            cons.setAccessible(true);
            instance2 = cons.newInstance();
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
		
		System.out.println("Hashcode of instance1: "+ instance1.hashCode());
		System.out.println("Hashcode of instance2: "+ instance2.hashCode());
	}
}

The output:

Hashcode of instance1: 366712642
Hashcode of instance2: 1829164700

How to prevent the reflection ?

You have to modify the constructor like below:

	private MySingleton() {
		//Prevent form the reflection api.
        if (instance != null){
            throw new RuntimeException("Use getMySingletonObject() method to get the single instance of this class.");
        }		
	}

It will throw an exception while someone tries to re-instantiates it.

How to make singleton Serialization proof?

Lets see what is Serialization and deserialization and how to do that:

class MySingleton implements Serializable{
	
	private volatile static MySingleton instance;
	private MySingleton() {
		//Prevent form the reflection api.
        if (instance != null){
            throw new RuntimeException("Use getMySingletonObject() method to get the single instance of this class.");
        }		
	}
	
	public static MySingleton getMySingletonObject() {
		
		if(instance == null) {
			synchronized(MySingleton.class) {
				if(instance == null) {
					instance = new MySingleton();
				}
			}
		}
		return instance;
	}	
}

public class Manager {	
	public static void main(String[] args) throws IOException , ClassNotFoundException{
		MySingleton instance1=MySingleton.getMySingletonObject();
		MySingleton instance2=null;
		
		ObjectOutput out = null;
        out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
        out.writeObject(instance1);
        out.close();
        //deserialize from file to object
        ObjectInput in = new ObjectInputStream(new FileInputStream("filename.ser"));
        instance2 = (MySingleton) in.readObject();
        in.close();
		
		System.out.println("Hashcode of instance1: "+ instance1.hashCode());
		System.out.println("Hashcode of instance2: "+ instance2.hashCode());
	}
}

Output:

Hashcode of instance1: 1550089733
Hashcode of instance2: 2003749087

To avoid the above you need to add a private readResolve() method in MySingleton class:

	private Object readResolve() {
		return getMySingletonObject();
	}

When an object is deserialized, the serialization mechanism checks if the class defines a readResolve() method. If it does, it invokes this method after the object is deserialized and uses the returned object instead of the deserialized one.
The full class would look like below:

class MySingleton implements Serializable{
	
	private volatile static MySingleton instance;
	private MySingleton() {
		//Prevent form the reflection api.
        if (instance != null){
            throw new RuntimeException("Use getMySingletonObject() method to get the single instance of this class.");
        }		
	}
	
	public static MySingleton getMySingletonObject() {
		
		if(instance == null) {
			synchronized(MySingleton.class) {
				if(instance == null) {
					instance = new MySingleton();
				}
			}
		}
		return instance;
	}
	
	//Make singleton from serialize and deserialize operation.
	protected Object readResolve() {
		return getMySingletonObject();
	}
}

How to make Singleton Cloning proof ?

Well it can break only if your MySingleton class has implemented the Cloneable interface, if it does not implement then no body can break it. Enjoy !!..

If your MySingleton class implements some other class which had implemented the Cloneable interface then what you can do ? You just override the clone() method and throw CloneNotSupportedException like below:

@Override
protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}

Copyright © 2025 .

Powered by PressBook Blog WordPress theme