Created
August 1, 2021 00:06
-
-
Save mertgunay/cdc70a5a0017672213be41e2cda9c85a to your computer and use it in GitHub Desktop.
Perfect Singleton Class for Java by Keval Patel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
// For explanation | |
// https://medium.com/@kevalpatel2106/how-to-make-the-perfect-singleton-de6b951dfdb0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment