Singleton Flashcards
Singleton pattern
used to create one and only instance of a class and a global point of access to it exists
examples of objects that should only have a single instance
Caches, thread pools, registries
how do we ensure that only one object ever gets created?
to make the constructor private of the class we intend to define as singleton
what happens when we make the constructor private of the class?
only the members of the class can access the private constructor
Two ways that may fix a race condition, under Multithreading conditions?
- add synchronized to the getInstance() method.
// Create a static method for object creation
synchronized public static AirforceOne getInstance() {
// Only instantiate the object when needed.
if (onlyInstance == null) {
onlyInstance = new AirforceOne();
}
return onlyInstance;
}
- undertake static initialization of the instance, which is guaranteed to be thread-safe// The sole instance of the class
private static AirforceOne onlyInstance = new AirforceOne();
What are the problems with “add synchronized to the getInstance() method” and “undertake static initialization of the instance” that may fix a race condition when the applications be under Multithreading condition?
synchronization is expensive and static initialization creates the object even if it’s not used in a particular run of the application
what is “double-checked locking” when the applications be under Multithreading condition?
synchronize only when the object is created for the first time and if its already created, then we don’t attempt to synchronize the accessing threads.
“double-checked locking
How “double-checked locking” is implemented in Java?
// The sole instance of the class. Note its marked volatile
private volatile static AirforceOneWithDoubleCheckedLocking onlyInstance;
// Create a static method for object creation
synchronized public static AirforceOneWithDoubleCheckedLocking getInstance() {
// Only instantiate the object when needed. if (onlyInstance == null) { // Note how we are synchronizing on the class object synchronized (AirforceOneWithDoubleCheckedLocking.class) { if (onlyInstance == null) { onlyInstance = new AirforceOneWithDoubleCheckedLocking(); } } } return onlyInstance; }
JVM volatile implementation for Java versions 1.4
will not work correctly for double checked locking
The double checked locking is now considered
an antipattern and its utility has largely passed away as JVM startup times have sped up over the years.
In the Java API we have the following singletons:
java.lang.Runtime
java.awt.Desktop