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

Synchronized Method  


Introduction
  • A synchronized method in Java is a method that is modified with the synchronized keyword.
  • It ensures that only one thread can access the method at a time for a particular object instance.
  • If another thread tries to call any synchronized method on the same object, it will be blocked until the first thread finishes execution.
  • Use of Synchronized Method :-
    1. Thread Safety
      • Prevents race conditions (when multiple threads modify shared data at the same time).
      • Ensures atomicity (a complete operation is executed without interruption).
    2. Mutual Exclusion (Mutex)
      • Provides exclusive access to shared resources (e.g., shared variables, files, database connections).
    3. Consistency of Data
      • Prevents data inconsistency caused by concurrent modifications.
    4. Easy to Use
      • Simpler to implement than using synchronized blocks manually, since the entire method becomes synchronized.
  • Syntax:-
    synchronized returnType methodName(parameters)
    {
        // method body
    }
  • Program:
    class BookMovieSeat
    {
        int total_seats=10;
    
        synchronized 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();
        }
    }
  • Explanation:
    • Here bookSeat() is a synchronized method, so only one thread can book seats at a time on the same BookMovieSeat object (bts).
    • This prevents both threads (Deepak and Amit) from booking seats simultaneously, which could have caused overbooking (race condition).
    • Because of synchronization:
      • When Deepak thread starts booking seats, Amit must wait until Deepak finishes execution of bookSeat().
      • After Deepak releases the lock, Amit will execute bookSeat(), and check the updated total_seats.
    • This ensures correct seat count, prevents inconsistent data, and avoids lost updates.

Disadvantages of Synchronization:
  • Synchronization is a very powerful concept in multithreaded programming as it resolves issues like race conditions, data inconsistency and thread interference.
  • But it has some disadvantages so it should be used carefully and only where necessary:
    1. Performance Overhead
      • Synchronization adds extra processing because acquiring and releasing locks takes time, which can slow down program execution.
    2. Reduced Concurrency
      • Only one thread can execute the critical section at a time, which may lead to under-utilization of CPU in multicore systems.
    3. Deadlock Risk
      • Incorrect use of synchronization can cause deadlocks, where two or more threads wait indefinitely for each other’s locks.
    4. Complex Debugging
      • Multithreaded programs with synchronization are harder to test and debug due to timing issues and thread interactions.
    5. Possibility of Starvation
      • Some threads may wait longer or even never get a chance to execute if lock acquisition is unfair.