About Synchronization
- Synchronization is the key concept in multi threaded application.
- Synchronization prevent threads interference.
- Synchronization is to guarantee atomic access to critical section of code.
- Synchronization provides following three function.
- Atomicity
- Ordering
- Visibility
- Synchronization is very important in JMM(Java Memory Model). It make the JVM to execute read
- Barrier and write Barrier.
- In read Barrier it invalidate the thread specific local memory ( processor cache or processor registers) and it make the processor to re read any variable used in synchronization block from main memory.
- Similarly, it makes the processor to execute write barrier to put back the thread local memory data back to main memory.
- It is recommended that synchronization code should be as minimum as possible.
- Synchronization can be apply to method or block or static method
public synchronized void processData(){
}
synchronized block
public void processData(){synchronized(this){
}
}
synchronized on static method
public synchronized static void processData(){ }
synchronized block on class level lock
public static void processData(){synchronized(Processor.class){
}
}