Skip to content

Instantly share code, notes, and snippets.

@alwarren
Created May 23, 2018 17:33
Show Gist options
  • Save alwarren/a4422621cbd135012260108d6b87e93d to your computer and use it in GitHub Desktop.
Save alwarren/a4422621cbd135012260108d6b87e93d to your computer and use it in GitHub Desktop.
Java thread-safe singleton
public class SingletonClass {
// dummy object for synchronization
private static final Object sLock = new Object();
// single instance of the class
private static SingletonClass INSTANCE;
public static SingletonClass getInstance() {
// force threads to wait until synchronized block completes
synchronized (sLock) {
if (INSTANCE == null) {
INSTANCE = new SingletonClass();
}
return INSTANCE;
}
}
// prevent instantiation outside of class
private SingletonClass() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment