Friday, 5 August 2011

Synchronization in Java

What is synchronization?
Threads communicate with each other by sharing access to fields and the objects reference fields refer to. (concurrent access to shared data).Though efficient, it can lead to thread interference and memory consistency errors. The tool to avoid these kind of errors in java is synchronization.

Why do we need to synchronize?
As said earlier, to avoid
  1. Thread interference: happens when two methods/operations running in two different threads but acting on same data, interleave.(i.e the sequence of steps interleave)
  2. Memory consistency errors:  occur when different threads have inconsistent views of what should be the same data.
Through the use of synchronization we can avoid the problem of  dirty data (This happens when the shared object is mutable) caused by multiple threads acting on the same data.  To avoid this, java uses monitors and 'synchronize' keyword to control access to a mutable shared object. Synchronization is not needed if you are using an immutable shared object or the shared object is used in read only mode.

What are the different ways/levels of synchronization can be applied in Java?
The synchronize keyword can be applied at the method level (coarse grained) or block of code (fine grained). 
  • If the keyword is applied to a static method then the lock is obtained on the class object (ex Account.getClass()).
  • If the keyword is applied on a non static method, then the lock is obtained on the instance of the object which contains synchronized code (ex obj1).
Any code which is written in the synchronized block has mutually exclusive lock on the object; which means that no other thread can access this critical section except the thread which is holding the lock. All other threads will have to wait till the lock is released.
It is usually a good practice to synchronize only that section of code which is critical rather than blocking the entire method ; reason synchronization comes with a performance cost.


Disadvantages of synchronization 

  1. There is a possibility of dead locks if not coded properly.
  2. Another problem with using it is performance; there is an overhead of obtaining locks.
References

No comments:

Post a Comment