Created
May 23, 2018 17:33
-
-
Save alwarren/a4422621cbd135012260108d6b87e93d to your computer and use it in GitHub Desktop.
Java thread-safe singleton
This file contains hidden or 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 { | |
// 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