Last active
August 30, 2024 19:22
-
-
Save saviomisael/0462489ab7024ac716eb4ec2f4086923 to your computer and use it in GitHub Desktop.
Singleton Thread-Safe 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
| import java.util.concurrent.locks.ReentrantLock; | |
| public class Singleton { | |
| private ReentrantLock lock = new ReentrantLock(); | |
| private Singleton instance = null; | |
| public Singleton getInstance() { | |
| // this creates an auxiliary variable to prevent another thread wait the synchronized block gets unlock | |
| Singleton result = instance; | |
| // this has concurrency issues, if result is not null this piece of code is not blocked by synchronized | |
| if(result == null) { | |
| // this is blocked by a thread | |
| synchronized(lock) { | |
| result = instance; | |
| // this check if result is nullable in a thread-safe way | |
| if(result == null) instance = result = new Singleton(); | |
| } | |
| } | |
| return result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment