Sunday, 29 September 2024

Singleton class with lazy and unbreakable

Lazy initialization single ton class

package com.example.practice.student.service;

public class SingletonClassExample {
private static volatile SingletonClassExample singletonClassExample;

private SingletonClassExample() {
}

public static synchronized SingletonClassExample getInstance() {
if (singletonClassExample == null) {
System.out.println("pawankumar");
return singletonClassExample= new SingletonClassExample();
//return singletonClassExample = new SingletonClassExample();
}
return singletonClassExample;
}

public void displayMsg() {
System.out.println("call from singleton class");
}

public static void displayMsg1() {
System.out.println("call from singleton class");
}
}


For Eager Initialization on declaration on instance variable  do assignment of object 


private static volatile SingletonClassExample singletonClassExample= new SingletonClassExample();



 unbreakable singleton class



package com.example.practice.student.service;

import java.io.Serializable;

public class UnbreakableSingClass implements Serializable,Cloneable {

private static UnbreakableSingClass unbrak;
private static boolean objectCreated=false;


private UnbreakableSingClass UnbreakableSingClass() {
if(objectCreated) {
throw new RuntimeException("objet");
}else {
return unbrak;
}
}

public static UnbreakableSingClass getIntanance() {
if(unbrak==null) {
synchronized (UnbreakableSingClass.class) {
if(unbrak==null) {
return unbrak=new UnbreakableSingClass();
}
}
}
return unbrak;
}

@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning of this singleton is not allowed.");
}

protected Object readResolve() {
return getIntanance();
}

}

No comments:

Post a Comment