Why is synchronization necessary? Explain with the help of a relevant example.

By | March 5, 2023

In Java, synchronization is necessary to ensure that multiple threads can access shared resources or critical sections in a safe and predictable manner. Without synchronization, multiple threads may concurrently access and modify the same data, leading to data inconsistency, race conditions, and other concurrency issues.

For example, consider a scenario where two or more threads are incrementing a counter variable, count, concurrently:

public class Counter {
private int count = 0;

public void increment() {

public int getCount() {
return count;

// usage:
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 10000; i++) {
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);

In the above example, the increment() method increments the count variable. If multiple threads invoke this method concurrently, they may end up overwriting each other’s changes and the final value of count may not be what we expect it to be. This is because the ++ operator is not an atomic operation in Java and may take several instructions to complete.

To ensure that the count variable is incremented correctly, we can add synchronization to the increment() method by using the synchronized keyword:

public synchronized void increment() {

With this change, only one thread can execute the increment() method at a time, while other threads are blocked until the method is released. This ensures that the count variable is incremented atomically and the final value of count will be the sum of all increments by all threads.

In summary, synchronization is necessary in Java to ensure thread safety and prevent concurrency issues when multiple threads access and modify shared resources. Without synchronization, concurrent access to shared data may lead to data inconsistency and race conditions. By using synchronization, we can ensure that critical sections of code are executed atomically by only one thread at a time.

You may also like:

What are fail-fast and fail-safe Iterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?
What are the important paradigms for Developing the Clean Object-Oriented Code?
What are new Features added in Java 8?


Leave a Reply

Your email address will not be published. Required fields are marked *