Thursday, 3 April 2014

Thread synchronization in Java - better approach

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;
}

No comments:

Post a Comment

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M