Created
August 25, 2025 10:47
-
-
Save manoelcampos/90671a0e3c3639e00082ef20c43d502d to your computer and use it in GitHub Desktop.
Shows the need for a double-checked lock when implementing a Singleton to ensure Thread-Safety
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 Singleton { | |
| private static volatile Singleton instance; | |
| // An id to make it clear multiple instances were created | |
| private final long id = System.nanoTime(); | |
| private Singleton(){ | |
| // Commented out just to demonstrate the problem with no double-checked locking | |
| //if(instance != null) throw new IllegalStateException("Singleton has already been created"); | |
| System.out.println("Creating Singleton with id " + id); | |
| } | |
| public static Singleton getInstance(){ | |
| if(instance == null){ | |
| synchronized(Singleton.class) { | |
| // Double-checked locking (commented out just to demonstrate that the check in the constructor isn't enough). | |
| // if(instance == null) | |
| instance = new Singleton(); | |
| } | |
| } | |
| return instance; | |
| } | |
| public static void main(String[] args) { | |
| for (int i = 0; i < 100; i++) { | |
| new Thread(Singleton::getInstance).start(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment