🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Synchronization in Java  


Problem Without Synchronization
  • Before learning synchronization, let us first discuss the problem that occurs without synchronization in real-world projects.
  • Problems in Booking Application:-
    • In real apps like IRCTC, MakeMyTrip or BookMyShow, every user's booking request is handled in a separate thread (or request handler).
    • Suppose there are 2 users i.e. Deepak (Thread-1) and Amit (Thread-2), both click “Book Movie” at the same time:
      • Both threads check → seat available → both book successfully.
      • Result: Multiple tickets can be issued for 1 seat → this is called data inconsistency (double booking).
      • This happens because:
        • The seat availability check and booking update are not atomic (not done one at a time).
        • Multiple threads are allowed to enter the critical section simultaneously.
    • Program:
      class BookMovieSeat
      {
          int total_seats=10;
      
          void bookSeat(int seats, String name)
          {
              if(total_seats>=seats)
              {
                  System.out.println(name+" booked "+seats+" seats successfully");
                  total_seats=total_seats-seats;
                  System.out.println("Total seats left : "+total_seats);
              }
              else
              {
                  System.err.println(name+" sorry...!! seats not left");
                  System.err.println("Total seats left : "+total_seats);
              }
          }
      }
      class MyThread extends Thread
      {
          BookMovieSeat bts;
          int seats;
      
          public MyThread(BookMovieSeat bts, int seats)
          {
              this.bts=bts;
              this.seats=seats;
          }
      
          public void run()
          {
              bts.bookSeat(seats, Thread.currentThread().getName());
          }
      }
      public class MovieBookingApp
      {
          public static void main(String[] args)
          {
              BookMovieSeat bts=new BookMovieSeat();
      
              MyThread deepak=new MyThread(bts, 6);
              deepak.setName("Deepak");
              deepak.start();
      
              MyThread amit=new MyThread(bts, 5);
              amit.setName("Amit");
              amit.start();
          }
      }
    • Note: The output may vary on different runs because multiple threads are executing in parallel.
  • Problems in the Above Program (Without Synchronization):
    1. Data Inconsistency:
      • Multiple threads may access and update total_seats at the same time, leading to wrong seat counts.
    2. Race Condition:
      • Two users may check availability simultaneously and both succeed in booking, even if seats are not enough.
    3. Overbooking Issue:
      • More seats may get booked than actually available.
    4. Unpredictable Output:
      • Since threads run in parallel, results may vary on every execution.
  • To solve these all problems, we have use synchronization.

Synchronization Introduction:
  • Synchronization is a mechanism in multithreaded programming that allows only one thread at a time to access a shared resource (critical section).
  • This helps prevent race conditions and ensures thread safety.
  • Advantages of Synchronization:
    1. Thread Safety
      • Prevents two threads from interfering with each other’s operations.
    2. Data Consistency
      • Ensures correct and predictable results in multithreaded programs.
    3. Race Condition Prevention
      • Allows only one thread at a time to access the critical section.
    4. Controlled Access
      • Helps manage critical resources efficiently.
    5. Reliability
      • Program behaves the same way every time, irrespective of CPU scheduling.
Types of Synchronization:
  • Synchronization in Java can be broadly divided into two main types based on what we are synchronizing:
    1. Process Synchronization
      • Ensures that multiple processes (not just threads) work together without conflicts.
      • Example: When multiple applications try to access the same file or database, process synchronization is used to maintain consistency.
      • Mostly handled by the Operating System (OS), not directly by Java.
    2. Thread Synchronization
      • Ensures that multiple threads of the same program access shared resources safely.
      • Prevents race conditions and ensures thread safety.
      • Types of Thread Synchronization:
        • Mutual Exclusion (Mutex): Allows only one thread at a time to access the critical section.
        • Cooperation (Inter-Thread Communication): Allows threads to communicate and coordinate with each other using wait(), notify() and notifyAll().
How to Achieve Synchronization:
Working of Synchronization:
  • Synchronization uses a lock (monitor) internally.
    • When a thread enters a synchronized method/block, it acquires the lock of the object (or class, for static methods).
    • Other threads that try to access the same synchronized method/block are blocked and must wait.
    • Once the first thread exits, it releases the lock, and one of the waiting threads gets a chance to acquire it and proceed.
    • Click Here for Program.