Java Reference
In-Depth Information
Implementing the Singleton Pattern in Plain Code
Because you need to guarantee that singletons serve only one instance, the i rst thing to do is
control the object's creation. You can do this easily by making the constructor invisible to the
outer world.
package com.devchronicles.singleton;
public class MySingleton {
private MySingleton() {
// Implemetation code here.
}
}
Next, you need a method that creates the instance or returns it if the instance was already created.
Because an instance of MySingleton does not yet exist, you must mark the creation method as static
to allow access via the class name; for example: MySingleton.getInstance() .
At comment 1 in Listing 4‐1, you test the creation of the singleton and create it if it does not exist;
otherwise, you return the instance that was created in a previous call to the getInstance() method.
Each subsequent calls returns the previously created MySingleton object instance. The code might
appear to be functioning, but it is actually buggy and not complete. Because the object creation
method is not atomic, it is prone to error in race conditions. It allows more than one instance of the
singleton to be created in a multithreaded environment.
LISTING 4‐1: Simple implementation of the singleton pattern
package com.devchronicles.singleton;
public class MySingleton {
private static MySingleton instance;
private MySingleton() {}
public static MySingleton getInstance() {
if (instance==null){ // 1
instance=new MySingleton();
}
return instance;
}
}
To i x the race condition problem, you need to acquire a lock and not release it until the instance
is returned. In Java, you can implement the locking mechanism via the synchronized keyword, as
shown in Listing 4‐2.
 
Search WWH ::




Custom Search