Open In App

Synchronization in Java

Last Updated : 04 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only one thread can access a resource at any given time. This process helps prevent issues such as data inconsistency and race conditions when multiple threads interact with shared resources.

Example: Below is a Java Program to demonstrate synchronization.

Java
class Counter {
    private int c = 0; // Shared variable

    // Synchronized method to increment counter
    public synchronized void inc() {
        c++;
    }

    // Synchronized method to get counter value
    public synchronized int get() {
        return c;
    }
}

public class Geeks {
    public static void main(String[] args) {
        Counter cnt = new Counter(); // Shared resource

        // Thread 1 to increment counter
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                cnt.inc();
            }
        });

        // Thread 2 to increment counter
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                cnt.inc();
            }
        });

        // Start both threads
        t1.start();
        t2.start();

        // Wait for threads to finish
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print final counter value
        System.out.println("Counter: " + cnt.get());
    }
}

Output
Counter: 2000

Explanation:

  • Two threads (t1 and t2) access a shared counter variable concurrently.
  • The inc() and get() methods are marked as synchronized.
  • synchronized ensures that only one thread can execute these methods at a time.
  • This prevents race conditions during concurrent updates.
  • The use of synchronization ensures the counter is accurately and consistently updated by both threads.
  • Final output reflects the correct cumulative result of all increments.

Synchronized Blocks in Java

Synchronized blocks in Java are marked with the synchronized keyword. All synchronized blocks synchronize on the same object and can only have one thread executed inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. If you want to master concurrency and understand how to avoid common pitfalls,

General Form of Synchronized Block

synchronized(sync_object)
{
// Access shared variables and other shared resources
}

Example: Below is an example of synchronization using Synchronized Blocks.

Java
class Counter {
    private int c = 0; // Shared variable

    // Method with synchronization block
    public void inc() {
        synchronized(this) { // Synchronize only this block
            c++;
        }
    }

    // Method to get counter value
    public int get() {
        return c;
    }
}

public class Geeks {
    public static void main(String[] args) {
        Counter cnt = new Counter(); // Shared resource

        // Thread 1 to increment counter
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                cnt.inc();
            }
        });

        // Thread 2 to increment counter
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                cnt.inc();
            }
        });

        // Start both threads
        t1.start();
        t2.start();

        // Wait for threads to finish
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print final counter value
        System.out.println("Counter: " + cnt.get());
    }
}

Output
Counter: 2000

Types of Synchronization

There are two type of synchronizations in Java which are listed below:

  • Process Synchronization
  • Thread Synchronization

1. Process Synchronization in Java

Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures that the shared resources are safe and in order.

Example: Here is a popular example of Process Synchronization in Java

Java
class BankAccount {
    private int balance
        = 1000; // Shared resource (bank balance)

    // Synchronized method for deposit operation
    public synchronized void deposit(int amount)
    {
        balance += amount;
        System.out.println("Deposited: " + amount
                           + ", Balance: " + balance);
    }

    // Synchronized method for withdrawal operation
    public synchronized void withdraw(int amount)
    {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount
                               + ", Balance: " + balance);
        }
        else {
            System.out.println(
                "Insufficient balance to withdraw: "
                + amount);
        }
    }

    public int getBalance() { return balance; }
}

// Main class
public class Geeks {
    public static void main(String[] args)
    {
        BankAccount account
            = new BankAccount(); // Shared resource

        // Thread 1 to deposit money into the account
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                account.deposit(200);
                try {
                    Thread.sleep(50); // Simulate some delay
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // Thread 2 to withdraw money from the account
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                account.withdraw(100);
                try {
                    Thread.sleep(
                        100); // Simulate some delay
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // Start both threads
        t1.start();
        t2.start();

        // Wait for threads to finish
        try {
            t1.join();
            t2.join();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print final balance
        System.out.println("Final Balance: "
                           + account.getBalance());
    }
}

Output
Withdrawn: 100, Balance: 900
Deposited: 200, Balance: 1100
Deposited: 200, Balance: 1300
Withdrawn: 100, Balance: 1200
Deposited: 200, Balance: 1400
Withdrawn: 100, Balance: 1300
Final Balance: 1300

Explanation:

  • Demonstrates process synchronization using a shared BankAccount object.
  • Two threads operate concurrently: one for depositing, one for withdrawing.
  • Both deposit() and withdraw() methods are marked as synchronized.
  • synchronized ensures mutual exclusion only one thread can access the balance at a time.
  • Prevents race conditions when threads access or modify the balance simultaneously.
  • Ensures thread safety and maintains a consistent, accurate account balance.

2. Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution of the threads in a multi-threaded program. There are two types of thread synchronization are mentioned below:

Example: Java Program to demonstrate thread synchronization for Ticket Booking System.

Java
class TicketBooking {
    private int availableTickets = 10; // Shared resource (available tickets)

    // Synchronized method for booking tickets
    public synchronized void bookTicket(int tickets) {
        if (availableTickets >= tickets) {
            availableTickets -= tickets;
            System.out.println("Booked " + tickets + " tickets, Remaining tickets: " + availableTickets);
        } else {
            System.out.println("Not enough tickets available to book " + tickets);
        }
    }

    public int getAvailableTickets() {
        return availableTickets;
    }
}

public class Geeks {
    public static void main(String[] args) {
        TicketBooking booking = new TicketBooking(); // Shared resource

        // Thread 1 to book tickets
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                booking.bookTicket(2); // Trying to book 2 tickets each time
                try {
                    Thread.sleep(50); // Simulate delay
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // Thread 2 to book tickets
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                booking.bookTicket(3); // Trying to book 3 tickets each time
                try {
                    Thread.sleep(40); // Simulate delay
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // Start both threads
        t1.start();
        t2.start();

        // Wait for threads to finish
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print final remaining tickets
        System.out.println("Final Available Tickets: " + booking.getAvailableTickets());
    }
}

Output
Booked 2 tickets, Remaining tickets: 8
Booked 3 tickets, Remaining tickets: 5
Booked 3 tickets, Remaining tickets: 2
Booked 2 tickets, Remaining tickets: 0
Final Available Tickets: 0

Explanation:

  • Uses a shared TicketBooking class with a synchronized bookTicket() method.
  • Ensures only one thread can book tickets at a time, preventing race conditions.
  • Multiple threads try booking tickets in a loop.
  • availableTickets is safely accessed and updated through synchronization.
  • Prevents overbooking and ensures thread-safe ticket allocation.
  • The program prints the remaining available tickets after all booking attempts.

Mutual Exclusion

Mutual Exclusion helps keep threads from interfering with one another while sharing data. There are three types of Mutual Exclusive mentioned below:

  • Synchronized method.
  • Synchronized block.
  • Static synchronization.

Example: Below is the implementation of the Java Synchronization.

Java
.import java.io.*;
// A Class used to send a message
class Sender {
    public void send(String msg)
    {
        System.out.println("Sending " + msg);  // Changed to print without new line
        try {
            Thread.sleep(100);
        }
        catch (Exception e) {
            System.out.println("Thread  interrupted.");
        }
        System.out.println(msg + "Sent");  // Improved output format
    }
}

// Class for sending a message using Threads
class ThreadedSend extends Thread {
    private String msg;
    Sender sender;

    // Receives a message object and a string message to be sent
    ThreadedSend(String m, Sender obj)
    {
        msg = m;
        sender = obj;
    }

    public void run()
    {
        // Only one thread can send a message at a time.
        synchronized (sender)
        {
            // Synchronizing the send object
            sender.send(msg);
        }
    }
}

// Driver class
class Geeks {
    public static void main(String args[])
    {
        Sender send = new Sender();
        ThreadedSend S1 = new ThreadedSend("Hi ", send);
        ThreadedSend S2 = new ThreadedSend("Bye ", send);

        // Start two threads of ThreadedSend type
        S1.start();
        S2.start();

        // Wait for threads to end
        try {
            S1.join();
            S2.join();
        }
        catch (Exception e) {
            System.out.println("Interrupted");
        }
    }
}

Output
Sending Hi 
Hi Sent
Sending Bye 
Bye Sent

Explanation:

  • Sender is synchronized inside run() to ensure thread safety.
  • Alternatively, making send() a synchronized method achieves the same.
  • This removes the need to synchronize Sender in run().
  • Both prevent concurrent access and ensure safe message sending.

We do not always have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods make this possible.

Example: Below is the Java program shows the synchronized method using an anonymous class

Java
import java.io.*;

class Test {
    synchronized void test_func(int n)
    {
        // synchronized method
        for (int i = 1; i <= 3; i++) {
            System.out.println(n + i);
            try {
                Thread.sleep(100);
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

// Driver Class
public class Geeks {
    // Main function
    public static void main(String args[])
    {
        // only one object
        final Test O = new Test();

        Thread a = new Thread() {
            public void run() { O.test_func(15); }
        };

        Thread b = new Thread() {
            public void run() { O.test_func(30); }
        };

        a.start();
        b.start();
    }
}

Output
16
17
18
31
32
33

Explanation:

  • The Test class defines a synchronized method test_func() to ensure thread safety.
  • Two threads are created using anonymous classes, each calling test_func() with different input values.
  • The synchronized keyword ensures only one thread accesses test_func() at a time.
  • This prevents interleaved output and ensures consistent execution of the number sequence.

Volatile Keyword

The volatile keyword in Java ensures that all threads have a consistent view of a variable's value. It prevents caching of the variable's value by threads, ensuring that updates to the variable are immediately visible to other threads.

Working of Volatile Modifier:

  • It applies only to variables.
  • volatile guarantees visibility i.e. any write to a volatile variable is immediately visible to other threads.
  • It does not guarantee atomicity, meaning operations like count++ (read-modify-write operations) can still result in inconsistent values

Example: Java program to demonstrate the volatile keyword.

Java
class Counter {
    private volatile boolean running = true;

    public void stop() {
        running = false;
    }

    public void start() {
        new Thread(() -> {
            while (running) {
                System.out.println("Running...");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println("Stopped.");
        }).start();
    }
}

public class Geeks {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        counter.start();

        Thread.sleep(600); // Let it run briefly
        counter.stop();    // Then stop the thread
    }
}

Output
Running...
Running...
Running...
Stopped.

Explanation:

  • running is marked volatile to ensure changes are visible across threads.
  • start() creates a thread that prints "Running..." while running is true.
  • Thread.sleep(200) slows the loop to simulate work.
  • main() waits briefly, then calls stop() to set running to false.
  • The thread sees the change and exits the loop, printing "Stopped.

Volatile vs Synchronized

Features

Synchronized

Volatile

Applies to

It applies only to blocks or methods.

It applies to variables only.

Purpose

It ensures mutual exclusion and visibility

It ensures visibility of changes to variables across threads

Performance

Performance is relatively low compared to volatile because of the acquisition and release of the lock.

Performance is relatively high compared to synchronized Keyword.


Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy