Created
August 21, 2018 03:09
-
-
Save mkdika/5bc3e6649165023c4afe0c1b2d6df876 to your computer and use it in GitHub Desktop.
Demo class for Double Check Locking Singleton Pattern in Java
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 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