Skip to content

Instantly share code, notes, and snippets.

@mkdika
Created August 21, 2018 03:09
Show Gist options
  • Save mkdika/5bc3e6649165023c4afe0c1b2d6df876 to your computer and use it in GitHub Desktop.
Save mkdika/5bc3e6649165023c4afe0c1b2d6df876 to your computer and use it in GitHub Desktop.
Demo class for Double Check Locking Singleton Pattern in Java
public final class DoubleCheckLockingSingleton {
private static volatile DummyService instance;
// to protect class from being new instance from outside of class
private DoubleCheckLockingSingleton() {
}
// singleton static method that use double check locking
// method are unable to overide
public static final DummyService getInstance() {
if (instance != null) return instance;
synchronized(TrueSingleton.class) {
if (instance == null) {
instance = new DummyService();
}
return instance;
}
}
}
// example for service class for instance in singleton class
class DummyService {
public void print(){
System.out.println("Print something!");
}
}
// driver class for demo
class DemoTrueSingleton {
public static void main(String[] args) {
TrueSingleton.getInstance().print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment