Synchronization deals with asynchronous behaviour of threads. It is a way of avoiding simultaneous access of two or more threads on a particular resource.
In Java, it is implemented in form of synchronized method and synchronized blocks.
Implementing synchronization in a code helps in dealing with critical section problem, where two or more threads together try to access a resource at the same time. To overcome from this problem, Synchronization is used.
Synchronization provides the capability to control the behaviour of thread efficiently. It works by giving a monitor or lock to a particular thread.
In other words, a thread when enters in a synchronized method or block, a unique lock gets assigned to it. Carrying lock signals other threads which also want to access that resource, to wait until the first thread completes its task and release its lock.
The lock concept enables us to achieve synchronous behaviour. However, the cons of this concept is that, it increases the waiting time of thread and the total execution time takes much longer than expected. And even sometimes it raises the situation of Deadlock.
Basis | Synchronized Method | Synchronized Block |
---|---|---|
Lock | Either Object level or Class level | On any object ( specified in parameter) |
Scope | On entire functionality, comparatively has greater scope | Only limited to some statement, comparatively has lesser scope |
Performance | Low | High |
Waiting time | High | Low |
nullPointerException | No | Yes |
A method with synchronized keyword allows only one thread at a time to let its task complete.
A thread that comes first would take the lock and perform its time, meanwhile other thread would wait for first thread to complete its task.
A Block with synchronized keyword allows only one thread at a time to let its task complete.
However, it follows the same concept as a synchronized method but it has limited scope as compared to the method.
The block itself is followed with an argument wrapping reference of an object.
It comes handy when less number of statements require to be synchronized.
Program:
class SynchronizationExample implements Runnable{ @Override public void run() { incrementMe(); unSynchronizedShowMe(); } synchronized void incrementMe() { for (int i = 0; i <= 7; i++) { System. out .println(Thread.currentThread().getName() + " is printing : " + i); } } void unSynchronizedShowMe() { System. out .println("unSynchronized : "+Thread.currentThread().getName()); synchronized (this) { try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } for(int i = 0; i<5;i++) System. out .println("printing from synchronized block : "+Thread.currentThread().getName()); } } public static void main(String[] args) { SynchronizationExample obj = new SynchronizationExample(); Thread threadOne = new Thread(obj,"Child One"); Thread threadtwo = new Thread(obj,"Child two"); threadOne.start(); threadtwo.start(); } }
Output:
This post was last modified on October 6, 2020