Java Synchronization

Introduction

Multithreading is one of Java’s most powerful features, allowing multiple threads to execute concurrently. While this improves application performance and responsiveness, it also introduces challenges when multiple threads access the same shared resource. If two or more threads modify shared data simultaneously, the application may produce incorrect or inconsistent results. This problem is known as a race condition.

To prevent such issues, Java provides a mechanism called Synchronization. Synchronization ensures that only one thread can access a critical section of code or a shared resource at a time, maintaining data consistency and thread safety.

What is Java Synchronization?

Java Synchronization is the process of controlling the access of multiple threads to shared resources so that only one thread can execute a critical section of code at a time.

Synchronization prevents:

  • Race conditions
  • Data inconsistency
  • Thread interference
  • Unexpected application behavior

Java uses an object’s monitor (lock) to implement synchronization. When a thread enters a synchronized block or method, it acquires the object’s lock. Other threads attempting to access the same synchronized resource must wait until the lock is released.

Why is Synchronization Needed?

Consider a bank account shared by two threads.

  • Thread A withdraws ₹500.
  • Thread B also withdraws ₹500 at the same time.
  • Account balance is ₹700.

Without synchronization, both threads may read the balance as ₹700 before either updates it, allowing both withdrawals to succeed. The final balance becomes incorrect.

With synchronization:

  • One thread completes the withdrawal first.
  • The second thread waits.
  • The updated balance is checked before the second withdrawal.

This ensures correct and predictable behavior.

Syntax

Synchronized Method


class MyClass {

    synchronized void display() {
        // Critical section
    }
}

Only one thread can execute the display() method on the same object at a time.

Synchronized Block


class MyClass {
    void display() {
        synchronized(this) {
            // Critical section
        }
    }
}

Only the code inside the synchronized block is locked.

How Synchronization Works

When a thread enters a synchronized method or block:

  1. The thread requests the object’s monitor lock.
  2. If the lock is available, it acquires the lock.
  3. The thread executes the synchronized code.
  4. After execution, the lock is released.
  5. Another waiting thread acquires the lock.

This mechanism ensures mutual exclusion, meaning only one thread can execute the protected code at a time.

Types of Synchronization

Java supports two primary types of synchronization.

1. Method Synchronization

An entire method is synchronized.

Example:


class Printer {
    synchronized void print() {
        for(int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Advantages:

  • Easy to implement
  • Protects the entire method

Disadvantages:

  • Locks the whole method, even if only part of it accesses shared data
  • May reduce performance

2. Block Synchronization

Instead of locking the whole method, only the critical section is synchronized.

Example:


class Printer {

    void print() {
        System.out.println("Preparing...");
        synchronized(this) {
            for(int i = 1; i <= 5; i++) {
                System.out.println(i);
            }
        }
        System.out.println("Completed.");
    }
}

Advantages:

  • Better performance
  • Smaller critical section
  • Reduced waiting time for other threads

Example: Without Synchronization


class Counter {

    int count = 0;

    void increment() {
        count++;
    }

}

public class Demo {

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

        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {

            for(int i = 0; i  {
            for(int i = 0; i < 1000; i++)
                counter.increment();
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.count);
    }
}

Possible Output

1875

The expected result is 2000, but because multiple threads update the shared variable simultaneously, some increments are lost.

Example: With Synchronization


class Counter {

    int count = 0;

    synchronized void increment() {
        count++;
    }

}

public class Demo {

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

        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {

            for(int i = 0; i  {

            for(int i = 0; i < 1000; i++)
                counter.increment();

        });

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

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

        System.out.println(counter.count);
    }
}

Output

2000

Since the increment() method is synchronized, only one thread updates the count variable at a time.

Static Synchronization

Static synchronization locks the Class object instead of an instance.

Example:


class Printer {

    synchronized static void print() {
        System.out.println("Printing...");
    }
}

Object Lock vs Class Lock

This is useful when protecting static variables shared across all instances of a class.

Feature Object Lock Class Lock
Lock Type Instance Class
Keyword synchronized instance method/block static synchronized method
Lock Object Current object (this) Class object
Shared Between Objects No Yes
Used For Instance variables Static variables

Advantages of Synchronization

  • Prevents race conditions
  • Maintains data consistency
  • Ensures thread safety
  • Protects shared resources
  • Simplifies concurrent programming
  • Prevents thread interference

Disadvantages of Synchronization

  • Reduces application performance
  • Threads spend time waiting for locks
  • Can lead to deadlocks if locks are acquired improperly
  • Increases complexity in multithreaded applications
  • Excessive synchronization can reduce scalability

Real-Life Example

Imagine an ATM connected to a bank account.

Two customers attempt to withdraw money from the same account simultaneously.

Without synchronization:

  • Both ATMs may read the same balance.
  • Both withdrawals succeed.
  • The account balance becomes incorrect.

With synchronization:

  • One ATM completes its transaction first.
  • The second ATM waits.
  • The updated balance is checked before processing the next withdrawal.

This ensures accurate account information.

Common Mistakes

1. Synchronizing the Entire Method Unnecessarily

Incorrect:


synchronized void display() {
    System.out.println("Start");
    calculate();
    System.out.println("End");
}

If only calculate() accesses shared data, synchronizing the whole method reduces performance.

2. Forgetting to Synchronize Shared Resources

Multiple threads modifying shared variables without synchronization can produce unpredictable results.

3. Synchronizing on the Wrong Object

Incorrect:


synchronized(new Object()) {
}

A new object is created every time, so threads do not share the same lock.

Correct:


synchronized(this) {
}

Or synchronize on another shared lock object.

4. Nested Locks Leading to Deadlock

Acquiring multiple locks in different orders across threads can cause deadlocks where each thread waits indefinitely for the other.

5. Overusing Synchronization

Synchronizing every method can significantly reduce concurrency and application performance. Synchronize only the code that truly requires mutual exclusion.

Best Practices

  • Synchronize only critical sections of code.
  • Prefer synchronized blocks over whole methods when appropriate.
  • Keep synchronized blocks as short as possible.
  • Avoid unnecessary locking.
  • Use private lock objects when suitable.
  • Consider higher-level concurrency utilities from java.util.concurrent (such as ReentrantLock, Semaphore, and ReadWriteLock) for complex scenarios.
  • Design classes to minimize shared mutable state whenever possible.

Synchronization vs Non-Synchronization

Feature Without Synchronization With Synchronization
Data Consistency Not guaranteed Guaranteed
Race Condition Possible Prevented
Thread Safety No Yes
Performance Faster Slightly slower due to locking
Shared Resource Protection No Yes

Conclusion

Java Synchronization is a fundamental concept in multithreading that ensures safe access to shared resources. By allowing only one thread at a time to execute critical sections, synchronization prevents race conditions, maintains data consistency, and makes applications thread-safe.

Java offers synchronization through synchronized methods, synchronized blocks, and static synchronization. While synchronization introduces some performance overhead, using it carefully and only where necessary helps build reliable and scalable concurrent applications. Understanding synchronization is essential for developing robust Java software and is a common topic in technical interviews.

Related Java Tutorials