Thursday 21 June 2012

Synchronization in Java

Synchronization refers to keeping multiple blocks in coherence with each other. The block that is surrounded by keyword synchronized can only be accessed by one entity at a time. When the entity requests access to the synchronized block and is granted access, a lock is set on the block. The lock gets released only when the entity that acquired the lock releases it. Synchronization is a must for mutual exclusion. In Java, implementing Synchronization is relatively simple compared to other programming languages. Synchronization in Java very important since Java supports multi-threading where multiple threads run in parallel to complete program execution. In a multi-threaded environment java object synchronization or class sync becomes very important

Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

Sample snippet for Synchronization in Java:

public class Count{
private static int count = 0;

public static synchronized int getCount(){
  return count;
}

public synchoronized setCount(int count){
   this.count = count;
}

}

No comments:

Post a Comment

Do you like our Content?