What is thread synchronization?
Suppose we have a multi-threaded application i.e. our application have more than one thread.Since we know multiple threads can share an object.Suppose we have an object which is shared by multiple threads because of this unexpected results can occur unless access to shared object is managed properly.For example:We have two threads which are going to update that shared object what will happen if one thread is updating that object and another thread is in process of updating that thread and another thread is going to read that data.Then what will happen,Which data the third thread will read?
Old data or first thread's data or second thread's data.
What will happen if third thread was supposed to read that old data but has read the new data either of first or second thread.So data is not correct.
The above problem can be solved by giving only one thread access to shared thread on time exclusive basis and at the same time if another thread wants to access that shared object then it has to wait until the thread with that exclusive lock has finished its operation.So this operation is called as Thread Synchronization.By synchronizing threads in this manner ensures that only one thread is using that shared object and other threads are waiting to access that object.This is called as Mutual Exclusion.
We need to synchronize only mutable data, there is no need to synchronize the immutable data.
How to perform synchronization?
Now we know basics of synchronization.Our next question is how to perform this synchronization in Java.
In Java,There is a concept of monitor.Each object has a monitor and a monitor lock(also known as intrinsic lock). This monitor is used to perform synchronization.Monitor ensures that the monitor lock is held by at most one thread at a time and this ensures mutual exclusion.If a thread want to access a shared object then it has to acquire the lock so that thread will be allowed to access that objects data.Other threads attempting to perform the operation which requires the same lock will be blocked until the first thread releases the lock and after that other thread can acquire the lock to perform operation.
The code which will be executed by the threads will be put in the synchronized block.The code inside the synchronized block is said to be guarded by the monitor lock.So thread has to acquire the lock in order to use that guarded block.
0 comments:
Post a Comment