Friday, 22 April 2016

What functionalities are provided by "synchronized" keyword ?


Java "synchronized" Keyword provides following functionality essential for concurrent programming :
 1) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.

 2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don't use  synchronized or volatile keyword.

 3) synchronized keyword involve locking and unlocking. Before entering into synchronized method or block thread needs to acquire the lock at this point. It reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.

Prior to Java 5, synchronized keyword in java was only way to provide synchronization of shared object. Any code written in synchronized block in java will be mutual exclusive and can only be executed by one thread at a time. You can have both static synchronized method and non static synchronized method and synchronized blocks in java but we cannot have synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of java synchronized variable you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don’t cache it locally.

Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method.

Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.