Sunday, 15 January 2012
Do you like this Article?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. So, its the mechanism that ensures that only one thread is accessed the resources at a time.
How to achieve synchronization in java?
In java, synchronization can be achieved by using the synchronized keyword.
It can be used in 2 ways.
1. on a method signature: We can declare synchronized keyword in method signature, therefore, that method will be thread safe in multi-threaded environment. That means, only, one thread at a time can access this method.
Below, method execute() is synchronized, so it is can be accessed by one thread at a time.
2. Write synchronized block: Secondly, we can write a synchronized block, and that block will be synchronized.
The above code, will lock the object itself, when this piece of code has been executed by a thread.