Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 37

Synchronization in Java

In this lesson: Fix race conditions in Java with synchronized methods and blocks — examples with before/after output. In Hindi & English.

Why synchronization

When multiple threads share the same data, they can interfere with each other and produce wrong results. Synchronization makes sure only one thread uses the shared data at a time, keeping it safe and consistent. It is essential in multithreaded programs.

💡 Synchronization = only one thread touches the shared data at a time, using a lock.

The race condition problem

class Counter {
    int count = 0;
    void increment() { count++; }   // not thread-safe
}
// If two threads call increment() together,
// some increments can be lost, giving a wrong total.

count++ looks simple, but it is really read-add-write. If two threads do it at once, one update can overwrite the other — a race condition that loses counts.

Synchronized method

class Counter {
    int count = 0;
    synchronized void increment() {   // thread-safe now
        count++;
    }
}

Adding synchronized to the method means only one thread can run it at a time. Others wait their turn, so every increment is counted correctly.

Synchronized block

void increment() {
    // ... other work that need not be locked ...
    synchronized (this) {     // lock only this part
        count++;
    }
}

A synchronized block locks only a chosen section, not the whole method. This is more precise: you lock just the shared-data part, letting the rest run freely for better performance.

How the lock works

Every object has an internal lock (monitor). When a thread enters a synchronized method or block, it acquires that object's lock. Other threads wanting the same lock must wait until it is released — which happens automatically when the synchronized code finishes.

When to synchronize

  • Shared, mutable data accessed by multiple threads — synchronize it.
  • Read-only data — no synchronization needed.
  • Keep locked sections small — lock only what must be protected, for speed.

Modern Java also offers higher-level tools like ConcurrentHashMap and the java.util.concurrent classes for common cases.

Common mistakes

  • Not synchronizing shared data. Leads to race conditions and wrong results.
  • Synchronizing everything. Slows the program — lock only what is needed.
  • Locking on different objects. Threads must share the same lock object to be safe.
  • Forgetting read-modify-write is not atomic. Even count++ needs protection.

Summary

  • Synchronization protects shared data across threads.
  • A race condition corrupts data when threads change it together.
  • synchronized lets only one thread run a method or block at a time.
  • A synchronized block locks a smaller, precise section.
  • Keep locked sections small and only protect shared, mutable data.

Next, revise threads in multithreading, or use a thread-safe map with HashMap vs Hashtable.

Frequently Asked Questions

What is synchronization in Java?
Synchronization controls access to shared data so that only one thread uses it at a time. This prevents threads from interfering with each other and corrupting the data — a common problem in multithreaded programs.
What is a race condition?
A race condition happens when two or more threads read and change the same data at the same time, and the final result depends on unpredictable timing. It leads to wrong, inconsistent values.
What does the synchronized keyword do?
synchronized makes a method or block usable by only one thread at a time, by acquiring a lock. Other threads must wait until the lock is released, which keeps shared data safe.
What is the difference between a synchronized method and block?
A synchronized method locks the whole method. A synchronized block locks only a chosen section of code on a specific object, which is more precise and can improve performance by locking less.
Does synchronization slow down a program?
It can, because threads may have to wait for the lock. So you synchronize only the parts that access shared data, keeping locked sections small to balance safety and speed.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicString vs StringBuffer vs StringBuilder Your progress: 37 / 61 (61%) · Lesson 38 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free