Singleton Class in Java - Spring Boot

A Singleton class in Java is a class that allows only one instance of itself to be created and provides a global point of access to that instance.

A Singleton class allows only one instance of the class to be created during the lifetime of an application.

Used when exactly one object is needed to coordinate actions across the system (e.g., logging, caching, configuration settings, etc.).

Singleton.java

				
					import java.io.Serializable;

public class Singleton implements Cloneable, Serializable{

	private static Singleton instance;

	private Singleton(){
		if(instance != null){
			throw new RuntimeException("Reflection is prevented");
		}
	}

	public static Singleton getInstance(){
		if(instance == null){
			synchronized(Singleton.class){
				if(instance == null){
					instance = new Singleton();
				}
			}
		}
		return instance;
	}

	public Object readResolve(){
		return instance;
	}

	public Object clone() throws CloneNotSupportedException{
		throw new RuntimeException("Clonning is prevented");
	}
}
				
			

Main.java

				
					import java.lang.reflect.Constructor;

public class Test {
    public static void main(String[] args) throws Exception {

        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();

        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());

        System.out.println(instance == instance2);

        Constructor<Singleton> declaredConstructor = Singleton.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);

        Singleton newInstance = declaredConstructor.newInstance();

        System.out.println(newInstance);
        System.out.println(instance == newInstance);

        Singleton clone = (Singleton)instance.clone();

        System.out.println(clone);
        System.out.println(clone == instance);
    }
}


				
			

Output:

				
					instance : 918221580
instance2 : 918221580
true
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
        at Test.main(Test.java:17)
Caused by: java.lang.RuntimeException: Reflection is prevented
        at Singleton.<init>(Singleton.java:9)
        ... 6 more
				
			
Scroll to Top