Wednesday, August 27, 2008

Using "synchronization" effectively

"Synchronization is anti-performance. So how can we use synchronization and still optimize on performance? So apply synchronization where it is absolutely necessary, or as minimum as possible."


We'll consider following two code snippets:

Scenario: Creating/accessing singleton object

Method level synchronization:



As you can see, the "synchronized" keyword is used at method level. So, now in multi-threaded environment, multiple threads accessing the getInstance() method will be queued-in. Following figure shows the scenario:



As shown in above figure, thread "t1" (the thread that is allowed to enter the getInstance() method first) will create the first object of "DemoClass" class and other threads will just get the reference of that singleton object which was created by thread "t1". Now this will definitely hamper the application's performance as every thread after "t1" will be queued-in, as there is no need after the singleton object is been created. So, we can use "synchronized" at block level which will reduce this performance bottle-neck. How, we'll see it soon :)

Block level synchronization:



As you can see, the "synchronized" keyword is used at block level. So, now in multi-threaded environment, multiple threads accessing the getInstance() method will NOT be queued-in. Following figure shows the scenario:



As shown in above figure, multiple threads can simultaneously access the getInstance() method. But, it can be that more than one threads can simultaneously hit the first "if statement". So, we can use "synchronized" keyword inside "if" such that those number of threads which are arrived parallel-ly can be queued-in. The second "if statement" makes sure that only one object is created as we're dealing with singleton class. Now, multiple threads can parallel-ly access the getInstance() method to get the reference of a singleton object. This removes the performance bottle-neck as mentioned in the above scenario.

Cool concept, isn't it :)


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________