Skip to content

Instantly share code, notes, and snippets.

@ngima
Last active April 17, 2017 04:58
Show Gist options
  • Save ngima/92a9afc7213d9aa6132a792b9c38fdd5 to your computer and use it in GitHub Desktop.
Save ngima/92a9afc7213d9aa6132a792b9c38fdd5 to your computer and use it in GitHub Desktop.
Singleton class that is thread, reflection and serialization safe
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