Skip to content

Instantly share code, notes, and snippets.

@saviomisael
Last active August 30, 2024 19:22
Show Gist options
  • Select an option

  • Save saviomisael/0462489ab7024ac716eb4ec2f4086923 to your computer and use it in GitHub Desktop.

Select an option

Save saviomisael/0462489ab7024ac716eb4ec2f4086923 to your computer and use it in GitHub Desktop.
Singleton Thread-Safe Java
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