Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java Synchronized Block
2.1.
Program
2.2.
Output
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Synchronization Block in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Multi-threaded programs frequently encounter situations when numerous threads attempt to access the same resources, resulting in erroneous and unexpected outcomes. When resources can be accessed concurrently, they can be used in an inconsistent fashion. To prevent this, we must control the access using the synchronization techniques.

To get a general idea about the problems that we will encounter without synchronization in multi-threaded programs, please refer to this blog, Synchronization in Java. This blog discusses Synchronization in general and discusses one of the techniques to achieve Synchronization in Java - Synchronized Methods.

Also Read About, Multithreading in java

Java Synchronized Block

In this blog, we will discuss one of the techniques offered in Mutual Exclusion to keep threads mutually exclusive. Mutual Exclusion helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:

 

  1. By Using Synchronized Method
  2. By Using Synchronized Block
  3. By Using Static Synchronization

 

In this blog, we will take up the method of Synchronized Blocks to achieve the principle of Mutual Exclusion in Multi-threading.

Synchronized block can be used to perform synchronization on any specific resource of the method. Suppose we have 20 lines of code in our method, but we want to synchronize only 10 lines, in such cases, we can use a synchronized block.

If we put all the codes of the method in the synchronized block, it will work the same as the synchronized method.

Program

//example of java synchronized method
class ResourceClass {

 int resource;

 ResourceClass(int val) {
   this.resource = val;
 }

 void UpdateandPrintResource(int n, int threadNum) {

   // Non-Synchronized Block
   System.out.println("Thread " + threadNum + " in non-synchronized block.");

   // Synchronized Block
   synchronized (this) {
     System.out.println("Thread " + threadNum + " Starts in Synchronized Block....");
     this.resource += n;
     try {
       Thread.sleep(400);
     } catch (Exception e) {
       System.out.println(e);
     }
     System.out.println("Value of Resource: " + this.resource);
     System.out.println("Thread " + threadNum + " Ends in Synchronized Block....");
   }
 }
}

class T1 extends Thread {

 ResourceClass t;

 T1(ResourceClass t) {
   this.t = t;
 }

 public void run() {
   t.UpdateandPrintResource(5, 1);
 }
}

class T2 extends Thread {

 ResourceClass t;

 T2(ResourceClass t) {
   this.t = t;
 }

 public void run() {
   t.UpdateandPrintResource(10, 2);
 }
}

public class TestSynchronization {

 public static void main(String args[]) {
   ResourceClass resoruceInst = new ResourceClass(10);
   T1 t1 = new T1(resoruceInst);
   T2 t2 = new T2(resoruceInst);
   t1.start();
   t2.start();
 }
}

Output

Practice it on online java compiler for better understanding.

Must Read Static Blocks In Java.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

1. What is Synchronization with Blocks in Java?
Ans: Synchronized block is used to lock an object for any shared resource. Scope of the synchronized block is smaller than the method. A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource.

 

2. Why do we need to use synchronization in multi-threaded programming?
Ans: We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource. If an Object is shared by multiple threads then there is need for synchronization in order to avoid the Object's state getting corrupted.

 

3. How to choose between Synchronized Blocks and Synchronized Methods?
Ans: If you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use a synchronized block. If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

Key Takeaways

This blog discussed the concept of Synchronization and one of the synchronization techniques offered by Java, Synchronized Blocks. We discussed the concept of Synchronization using Blocks in multi-threaded programming in detail with the help of an example program as well. 

We hope that this blog has helped you enhance your knowledge regarding Synchronization using Blocks in Java. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Coding!

Previous article
Difference between Wait and Sleep in Java
Next article
Static Synchronisation in Java
Live masterclass