Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem without Synchronization
3.
Concept of Synchronization
4.
Locks in Java
5.
Java Synchronized Method
5.1.
Program:
5.2.
Output:
5.3.
Program:
5.4.
Output:
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Synchronization 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 synchronization techniques.

In this blog, we will discuss the concept of Synchronization in general and why it is crucial for the working of Multi-threaded programs. We will also discuss one of the synchronization techniques offered by Java - Synchronized Methods.

Problem without Synchronization

Let us imagine a multi-threaded program with two threads T1 and T2 involving a shared resource R. Let us consider the following sequence of events that occurs during the execution of the program.

Event 1: T1 accesses the value of R.

Event 2: T2 accesses the value of R.

Event 3: T1 increments the value of R by 1 and updates it.

Event 4: T2 also increments the value of R by 1 and updates it.

Ideally, the final value of R should be incremented by 2. But given the sequence of events, it will be incremented by only 1, thus giving erroneous results. This happens because, before the value of Resource R is updated in Event 3, it is accessed by T2, which is not desirable.

Ideally, while the thread T1 is not done with handling/updating Resource R, no other thread should be allowed to access its value.

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

Concept of Synchronization

Synchronization in Java refers to the ability to govern different threads' access to a shared resource. When we only want one thread to access a shared resource, Java Synchronization is a better solution. The basic purpose of synchronization is to avoid thread interference and solve the random-access problem. This blog is mainly concerned with Thread Synchronization Techniques. 

There are two types of thread synchronization:

  1. Mutual Exclusion(When only one thread is allowed to access a shared space, resource, etc.)
  2. Cooperation(or Inter-thread communication)

 

In this blog, we will discuss one of the techniques offered in Mutual Exclusion to keep threads mutually exclusive. Mutual Exclusive 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 Method to achieve the principle of Mutual Exclusion in Multi-threading.

You can also read about the Multiple Inheritance in Java.

Locks in Java

Synchronization is based on a lock or monitor, which is an internal entity. A lock is associated with every object. By convention, a thread that requires consistent access to an object's fields must first obtain the object's lock and then release the lock after it's finished. All other threads attempting to access the object’s field are blocked until the thread currently holding the object’s lock releases it.

The package java.util.concurrent.locks contain many lock implementations starting with Java 5.

Java Synchronized Method

If you declare any method as synchronized, it is known as a synchronized method. The synchronized method is used to lock an object for any shared resource. When a thread calls a synchronized method, the lock for that object is automatically acquired and released when the thread completes its task.

Let us first try this multi-threaded program without synchronization and Try it on java online compiler.

Program:

//Example of Java Synchronized Method
class ResourceClass {

 int resource;

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

 void UpdateandPrintResource(int n, int threadNum) {
   System.out.println("Thread " + threadNum + " Starts....");
   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....");
 }
}

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:

As you can see, there is no order in which the object is accessed and its function is called. This is the problem with no synchronization, there is no consistency in the order of accessing and updating any resource.

Now let us see the same program with the synchronized method.

Program:

//Example of Java Synchronized Method
class ResourceClass {

 int resource;

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

 synchronized void UpdateandPrintResource(int n, int threadNum) {
   System.out.println("Thread " + threadNum + " Starts....");
   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....");
 }
}

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:

 

Must Read Static Blocks In Java.

FAQs

1. What is Synchronization in Java?
Ans: Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. Synchronization is necessary for reliable communication between threads.

 

2. Why do we need to use synchronization in multithreaded 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 a need for synchronization in order to avoid the Object's state getting corrupted.


3. Is Vector synchronized?
Ans: Vector is synchronized, which means only one thread at a time can access the code, while ArrayList is not synchronized, which means multiple threads can work on ArrayList at the same time.

Key Takeaways

This blog discussed the concept of Synchronization and one of the synchronization techniques offered by Java, Synchronized Methods. We discussed the importance of Synchronization techniques 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 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!

Next article
Difference between Wait and Sleep in Java
Live masterclass