Synchronization: The Public Bathroom

Synchronization: The Public Bathroom in Java: Imagine a Public Bathroom with only one toilet.

Concept Explanation

Imagine a Public Bathroom with only one toilet. If three people try to use it at the exact same time, you have a "Race Condition" and a very big mess.

To prevent this, you use a Lock. When one person goes in, they lock the door. The others must wait outside (they are "Blocked") until the door is unlocked.


Syntax or Core Structure

In Java, we use the synchronized keyword to lock a method or a block of code.

public class BankAccount {
    private int balance = 100;

    // Only ONE thread can run this at a time
    public synchronized void withdraw(int amount) {
        if (balance >= amount) {
            balance -= amount;
        }
    }
}

Common Mistakes

  • Deadlock: Imagine Person A is waiting for Person B to finish, but Person B is waiting for Person A to finish. Neither ever moves.
  • Performance Overload: If you synchronize everything, your program becomes single-threaded and slow. Only lock what is absolutely necessary.

Practice Exercises

  1. The Counter Clash: Create a simple Counter class with a count variable. Run 10 threads that each increment it 1000 times without synchronization. What is the final count? Now add synchronized and see the difference.
  2. Synchronized Block: Research how to use a synchronized(this) { ... } block inside a method instead of synchronizing the whole method. Why is this better for performance?
  3. The Deadlock Challenge: Research the "Dining Philosophers" problem. How does it illustrate the danger of synchronization?