Synchronization

All Java Topics
Last updated: May 25, 2026
Author: ManaCoding Team

Synchronization in Java is a mechanism used to control access of multiple threads to a shared resource. It helps prevent data inconsistency and race conditions.

📝 Syntax
synchronized void methodName() {
  // critical section
}
💻 Example Program
class Counter {

  int count = 0;

  synchronized void increment() {
    count++;
  }

}

class MyThread extends Thread {

  Counter c;

  MyThread(Counter c) {
    this.c = c;
  }

  public void run() {
    for (int i = 1; i <= 1000; i++) {
      c.increment();
    }
  }

}

public class Main {

  public static void main(String[] args) throws Exception {

    Counter c = new Counter();

    MyThread t1 = new MyThread(c);
    MyThread t2 = new MyThread(c);

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    System.out.println("Final Count: " + c.count);

  }

}

// Output:
// Final Count: 2000
💡 What is Synchronization?
  • 1 Controls access to shared resources.
  • 2 Ensures thread safety.
  • 3 Prevents race conditions.
  • 4 Works with locks in JVM.
💡 Types of Synchronization
  • 1 Method synchronization.
  • 2 Block synchronization.
  • 3 Static synchronization.
  • 4 Object-level locking.
💡 Why Synchronization is Needed?
  • 1 To avoid data inconsistency.
  • 2 To prevent race conditions.
  • 3 To ensure thread safety.
  • 4 To manage shared resources.
💡 Synchronization Problems
  • 1 Deadlock – threads waiting forever.
  • 2 Starvation – thread never gets access.
  • 3 Performance overhead.
  • 4 Reduced concurrency.
Quick Summary
  • Synchronization controls thread access to shared resources.
  • It prevents race conditions.
  • It ensures thread safety.
  • But may reduce performance if overused.
FAQs
What is synchronization in Java?
It is a mechanism to control access of multiple threads to shared resources.
Why is synchronization needed?
To prevent data inconsistency and race conditions.
What is a race condition?
A situation where multiple threads access shared data simultaneously causing incorrect results.
What is a synchronized method?
A method that allows only one thread at a time to access it.
What is deadlock?
A situation where threads are waiting forever for each other.
🎯 Interview Questions
Q1. What is synchronization in Java?
Answer: It is a mechanism to control access of multiple threads to shared resources.
Q2. Why is synchronization needed?
Answer: To prevent data inconsistency and race conditions.
Q3. What is a race condition?
Answer: A situation where multiple threads access shared data simultaneously causing incorrect results.
Q4. What is a synchronized method?
Answer: A method that allows only one thread at a time to access it.
Q5. What is deadlock?
Answer: A situation where threads are waiting forever for each other.
Quiz

What does synchronization prevent?