Last active
April 17, 2017 04:58
-
-
Save ngima/92a9afc7213d9aa6132a792b9c38fdd5 to your computer and use it in GitHub Desktop.
Singleton class that is thread, reflection and serialization safe
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
import java.io.Serializable; | |
public class Singleton implements Serializable { | |
private static volatile Singleton sInstance; | |
private Singleton() { | |
if (sInstance != null) { | |
throw new RuntimeException("Use getInstace() method to instantiate.") | |
} | |
} | |
public static synchronized Singleton getInstance() { | |
if (sInstance == null) { | |
synchronized (Singleton.class) { | |
if (sInstance == null) { | |
sInstance = new Singleton(); | |
} | |
} | |
} | |
return sInstance; | |
} | |
public Singleton readResolve() { | |
return getInstance(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment