Skip to content

Instantly share code, notes, and snippets.

@kevalpatel2106
Last active May 25, 2020 05:04
Show Gist options
  • Save kevalpatel2106/77d9db74fea4027cca24c7473f072c95 to your computer and use it in GitHub Desktop.
Save kevalpatel2106/77d9db74fea4027cca24c7473f072c95 to your computer and use it in GitHub Desktop.
public class SingletonClass implements Serializable {
private static volatile SingletonClass sSoleInstance;
//private constructor.
private SingletonClass(){
//Prevent form the reflection api.
if (sSoleInstance != null){
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance() {
if (sSoleInstance == null) { //if there is no instance available... create new one
synchronized (SingletonClass.class) {
if (sSoleInstance == null) sSoleInstance = new SingletonClass();
}
}
return sSoleInstance;
}
//Make singleton from serialize and deserialize operation.
protected SingletonClass readResolve() {
return getInstance();
}
}
@codefarm0
Copy link

I followed the example but couldn't enforce singleton here also.
readResolve() method should have Object return type.

@ani03sha
Copy link

ani03sha commented Sep 9, 2019

@greenlearner01 is right. readResolve() methos should have java.lang.Object return type to enforce singleton.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment