synchronized block – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 06 Oct 2020 04:44:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg synchronized block – Programmerbay https://programmerbay.com 32 32 Difference between synchronized block and synchronized method in Tabular form https://programmerbay.com/synchronized-method-vs-synchronized-block/ Thu, 05 Mar 2020 17:55:54 +0000 https://programmerbay.com/?p=6158 What is Synchronization?

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.

Difference between Synchronized Method and Synchronized Block in Tabular form

BasisSynchronized MethodSynchronized Block
Lock Either Object level or Class level On any object ( specified in parameter)
Scope On entire functionality, comparatively has greater scopeOnly limited to some statement, comparatively has lesser scope
PerformanceLowHigh
Waiting timeHighLow
nullPointerExceptionNoYes

Synchronized Method

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.

Synchronized Block

 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.

Java program to demonstrate the working of synchronized method and synchronized block ?

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:

method


Key Differences

  • A synchronized method provides a lock corresponding to object-level or Class level ( i.e class level means static method ), whereas, synchronized block provides a lock on any object depending on the parameter.
  • A synchronized method imposes lock on entire functionality of the respective method, while the synchronized block is used to lock a lesser number of consecutive statements ( Critical section area).
  • Since, the synchronized method provides a lock on current instance otherwise class level, therefore,  nullPointerException can’t be expected. On the other hand, if the parameter evaluated as null, then there would be likely a nullPointerException occurred.
  • Synchronized block boosts the performance of a respective program as it is intended to use on an only certain part of the program, rather than the entire method. Whereas the synchronized method locks entire functionality even though, some part of code has nothing to do with write or update.
  • Since, performance has an indirect relation with waiting time. In other words, the synchronized method increases the waiting time, whereas synchronized block has an advantage over the method as its scope is limited and smaller than the method.

]]>