1. Singleton
Singleton pattern in java enterprise world
Slim Ouertani
2. Intent
Ensure a class only has one instance, and
provide a global point of access to it. [GoF p
119]
3. Motivation
It's important for some classes to have exactly one
instance. Although there can be many printers in a
system, there should be only one printer spooler.
How do we ensure that a class has only one instance
and that the instance is easily accessible?
A global variable makes an object accessible, but it
doesn't keep you from instantiating multiple objects.
4. Motivation
A better solution is to make the class itself responsible
for keeping track of its sole instance.
The class can ensure that no other instance can be
created (by intercepting requests to create new
objects), and it can provide a way to access the
instance.
This is the Singleton pattern.
5. HOW ?
Before release 1.5, there were two ways to
implement singletons.
Both are based on keeping the constructor
private and exporting a public static member to
provide access to the sole instance.
In one approach, the member is a final field
6. Singleton with public final field
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public void leaveTheBuilding() { ... }
}
Reflexion!!!
8. singleelement enum type
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
JAVA 5
9. Lazy initialization
Lazy initialization is the act of delaying the initialization
of a field until its value is needed.
If the value is never needed, the field is never
initialized.
Lazy initialization is a doubleedged sword. It
decreases the cost of initializing a class or creating an
instance, at the expense of increasing the cost of
accessing the lazily initialized field.
In the presence of multiple threads, lazy initialization is
tricky.
10. Lazy initialization of instance field
synchronized accessor
private static Elvis elvis;
synchronized static Elvis getElvis() {
if (elvis == null)
elvis = new Elvis();
return elvis;
}
Slow!!!
11. DoubleChecked Locking idiom
DCL
static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance == new Singleton();
}
}
return instance;
}
No java 1.4!!!