Singleton Pattern
Definition
Ensures that a class has only one instance, and
provides a global point of access to it
• There are two main points in the definition
• make it impossible to instantiate a class more than
once
• global access to this one instance
How to prevent an object
from being instantiated
more than one
Step 1: Private Constructor
• Use a private constructor
• This means that the constructor can only be called from
the class itself
public Singleton {
private Singleton(){}
}
Step 2: make the class responsible
for creating an instance of itself
• Add a static method inside the class, and make this method responsible to
making the instance
• return an object of type Singleton (class name)
• not enough : we can call Singleton.getInstance() as much as we want
public Singleton {
private Singleton(){}
public static Singleton getInstance (){
return new Singleton // not enough
}
Step 3:Make Sure to Create
One Instance
• Define a static variable to hold the one instance of the class Singleton
• in the getInstance method create an instance of the class Singleton if
it is not instantiated
public Singleton {
private static Singleton uniqueInstance ;
private Singleton(){}
public static Singleton getInstance (){
if (uniqueInstance == null){
uniqueInstance = new Singleton();//call the private constructor
return uniqueInstance;
this type of initialization is called lazy
}
initialization, created when requested
}
Singleton & Multithreading
• Change the getInstance method to be Synchronized
• Adding synchronized will force every thread to wait for its
turn before entering the getInstance method
public Singleton {
private static Singleton uniqueInstance ;
private Singleton(){}
public static Synchronized Singleton getInstance (){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
return uniqueInstance;
}
Notes On Synchronization
• What to do
1. nothing if the performance is not an issue just use the synchronization as shown in
the previous slide
2. use eagerly approach to create the instance
3. double-checked locking
Eager Instantiation
• Create the instance from the beginning
• Any class wants an instance will get the same instance
public Singleton {
private static Singleton uniqueInstance = new Singleton() ;
private Singleton(){}
public static Singleton getInstance (){
return uniqueInstance;
• This considered a waste of resources, the instance might not be
needed
double-checked locking
• volatile indicates that the value public Singleton {
of the variable will be modified private volatile static Singleton uniqueInstance ;
private Singleton(){}
by multithreads
public static Singleton getInstance (){
if (uniqueInstance == null){
• synchronize only if the synchronized(Singleton.class){
if (uniqueInstance == null){
uniqueInstance is null
uniqueInstance = new Singleton();
• if it is not null, the created }
instance will be returned
return uniqueInstance;
• If null synchronize and check
}
again to make sure that
uniqueInstance is still null