Following is the getInstance method to get the Singleton Object. The advantage of this logic is we avoid checking for the synchronization for every call to getInstance.
Singleton getInstance()
{
synchronize
{
if(instance == null)
{
instance = new Singleton();
}
}
return instance;
}
In the above code, we always get into synchronization block even though its not required for every call.
To avoid this modify the above code like
Singleton getInstance()
{
if(instance == null) //Additional check to not enter into synchronization block.
{
synchronize
{
if(instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
Singleton getInstance()
{
synchronize
{
if(instance == null)
{
instance = new Singleton();
}
}
return instance;
}
In the above code, we always get into synchronization block even though its not required for every call.
To avoid this modify the above code like
Singleton getInstance()
{
if(instance == null) //Additional check to not enter into synchronization block.
{
synchronize
{
if(instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
No comments:
Post a Comment