February 28, 2017


What is Synchronization?

Synchronization is the mechanism to control the access of multiple threads on a shared resource or on a block of code. In java synchronization can be achieved using synchronized keyword.

Why Synchronization is required?

Synchronization is required when java objects are shared among multiple threads to avoid any corruption of state of abject. If object is read-only or immutable object you don’t required synchronizing your code in multiple threads.

How Synchronization works?

Synchronization in java works with object locks. Every object has its own lock and one lock per object. When you enter the synchronized method, you automatically acquire a lock on a current object of the class. If one thread has acquires the lock no other thread can get the lock or can enter the synchronized block until first thread releases the lock.  Once the thread completes the execution of synchronized block, it releases the lock.

 Two ways to synchronize code

It’s always better to synchronize block of code rather than a method.   If you don’t want to synchronize entire method you can just synchronize block of code. Synchronization does hurt concurrency and performance hit, so it’s better to synchronize code only required part. The two ways to synchronize the code is shown below.

Synchronizing a Method

Below code shows how to synchronize a method. It acquires a lock on the object used to invoke the method.

 Synchronizing a Block

If you synchronize the block of code it acquires the lock on this (current) object.


Synchronizing static methods

The static methods can also be synchronized. The static synchronized method will have lock on class instance java.lang.Class. One lock per class. Threads accessing static synchronized method will always block each other in the same class.


Some points to remember about Synchronization.

1.  Only methods or blocks can be synchronized.

2.  A class can have both synchronized and non-synchronized methods and multiple threads can still access the class’s non-synchronized method.

3. One lock per object.

4.  A thread can acquire more than one lock.

5. If thread has a lock and goes to sleep, it will not release the lock.

6. A static synchronized method and non-static synchronized method will not block each other because static method locks on class instance and not-static method on this instance.

Thread Deadlock

Deadlock occurs when two threads are waiting for each other to releases the lock forever.

Leave a Reply