It is advisable to
initialize the object only when it’s required. Delay initialization required
additional consideration to ensure that integrity of the singleton is
maintained even in concurrent access.
Code snippet:
The integrity of
singleton object in multi-threaded environment can be sustain by declaring
getInstance() as synchronize method.
public class Singleton
{
//Declaring singleton field as static field
//This field has static nature and will shared among all
//instance of this class.
private static Singleton singleton=null;
//restrict object creation to this class only
// Private access modifier play the critical role
// to restrict the access of the constructor to the outsider.
private Singleton()
{
}
// Obtain instance of Singleton class with the help of
// Singleton.getInstance() method.
public static synchronized Singleton getInstance()
{
if(singleton==null)
{
singleton=new Singleton();
}
return singleton;
}
/// clone() method ....
// additional stuff ...
}
Key points:
- Singleton object is thread safe
- Only one thread will execute the getInstance() method that will reduce the concurrency.
- Every time getInstance() method is called additional housekeeping task executed to achieve mutual exclusion among the thread
Posted in: