Java Synchronization

Su Suriya Ravichandran Updated 18 Nov 2026
15 min read ·Lesson 189 of 306

Java synchronization controls how threads access shared data, so that only one thread at a time can run a critical piece of code. Without it, two threads that change the same variable at the same moment can overwrite each other's work and leave the data in a broken state.

Java provides synchronization through the synchronized keyword, the wait()/notifyAll() methods, and lock classes such as ReentrantLock. This lesson shows each of them with runnable examples.


Why Java Synchronization Is Needed

The statement visits++ looks like one step, but the CPU does three: read the value, add one, and write it back. If two threads do this at the same time, both can read the same old value, and one increment is lost.

public class UnsafeCounter {
    private int visits = 0;

    void recordVisit() {
        visits++; // read, add one, write back: three steps, not one
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeCounter counter = new UnsafeCounter();
        Runnable task = () -> {
            for (int i = 0; i < 1_000_000; i++) {
                counter.recordVisit();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("expected: 2000000");
        System.out.println("actual  : " + counter.visits);
    }
}

Output (the actual number changes on every run):

expected: 2000000
actual  : 1967073

How it works:

  • Two threads each call recordVisit() one million times on the same object.
  • Sometimes both threads read, say, 500, both write 501, and one visit disappears. Thousands of updates are lost this way.
  • This kind of bug is called a race condition. It is hard to find because the result is different on every run, and sometimes it is correct by luck.

Java synchronized Method

Adding synchronized to an instance method makes a thread take the object's lock (also called its monitor or intrinsic lock) before running the method, and release it when the method returns. While one thread holds the lock, other threads that call any synchronized method of the same object must wait.

synchronized returnType methodName(parameters) {
    // only one thread at a time per object runs this
}
public class SyncMethodCounter {
    private int visits = 0;

    synchronized void recordVisit() { // only one thread at a time per object
        visits++;
    }

    synchronized int getVisits() {    // reads are synchronized too
        return visits;
    }

    public static void main(String[] args) throws InterruptedException {
        SyncMethodCounter counter = new SyncMethodCounter();
        Runnable task = () -> {
            for (int i = 0; i < 1_000_000; i++) {
                counter.recordVisit();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("expected: 2000000");
        System.out.println("actual  : " + counter.getVisits());
    }
}

Output:

expected: 2000000
actual  : 2000000

How it works:

  • recordVisit() is synchronized, so the read-add-write sequence can no longer be interrupted halfway by the other thread.
  • getVisits() is also synchronized. Taking the same lock for reading guarantees the reader sees the latest value written by other threads.
  • While one thread waits for the lock, it is in the BLOCKED state described in Java Thread States.

Java synchronized Block

A synchronized block locks only part of a method, and lets you choose which object to lock on. Keeping the locked section small means threads wait for each other less.

synchronized (lockObject) {
    // only one thread at a time per lockObject runs this
}
import java.util.ArrayList;
import java.util.List;

public class SyncBlock {
    private final Object lock = new Object();       // private lock object
    private final List<String> auditLog = new ArrayList<>();
    private int processedOrders = 0;

    void processOrder(String orderId) {
        // Slow work that does not touch shared data: no lock needed
        String invoice = "INV-" + orderId.toUpperCase();

        synchronized (lock) { // lock only the part that changes shared state
            processedOrders++;
            auditLog.add(invoice);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SyncBlock shop = new SyncBlock();
        Thread[] cashiers = new Thread[4];

        for (int c = 0; c < cashiers.length; c++) {
            int cashierId = c;
            cashiers[c] = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    shop.processOrder("c" + cashierId + "-" + i);
                }
            });
            cashiers[c].start();
        }
        for (Thread cashier : cashiers) {
            cashier.join();
        }

        synchronized (shop.lock) {
            System.out.println("processed orders: " + shop.processedOrders);
            System.out.println("audit log size  : " + shop.auditLog.size());
        }
    }
}

Output:

processed orders: 4000
audit log size  : 4000

How it works:

  • Building the invoice text uses only local variables, so it runs outside the lock and four cashier threads can do it in parallel.
  • Only the two lines that change shared state (processedOrders and auditLog) are inside synchronized (lock).
  • lock is a private final Object. Because no outside code can see it, no other code can accidentally hold it and slow this class down.
  • main reads the results inside the same lock after joining the threads, which is safe and consistent.

Note: Always lock on a final field. If the field could be reassigned, two threads might lock on two different objects and both enter the "protected" code at the same time.


Static synchronized Methods: The Class Lock

A static synchronized method locks the class object (StaticSync.class) instead of an instance. All callers share that single lock, which protects static fields.

public class StaticSync {
    private static int nextInvoiceNumber = 1000;

    // static synchronized locks on StaticSync.class, shared by ALL instances
    static synchronized int nextInvoice() {
        return nextInvoiceNumber++;
    }

    public static void main(String[] args) throws InterruptedException {
        int[] issuedByA = new int[500];
        int[] issuedByB = new int[500];

        Thread a = new Thread(() -> {
            for (int i = 0; i < issuedByA.length; i++) issuedByA[i] = nextInvoice();
        });
        Thread b = new Thread(() -> {
            for (int i = 0; i < issuedByB.length; i++) issuedByB[i] = nextInvoice();
        });
        a.start();
        b.start();
        a.join();
        b.join();

        java.util.Set<Integer> unique = new java.util.HashSet<>();
        for (int n : issuedByA) unique.add(n);
        for (int n : issuedByB) unique.add(n);

        System.out.println("invoice numbers issued: " + (issuedByA.length + issuedByB.length));
        System.out.println("unique numbers        : " + unique.size());
        System.out.println("next number           : " + nextInvoice());
    }
}

Output:

invoice numbers issued: 1000
unique numbers        : 1000
next number           : 2000

How it works:

  • nextInvoiceNumber is static, shared by the whole program.
  • nextInvoice() is static synchronized, so two threads can never receive the same number.
  • All 1000 issued numbers are unique, and the counter moved from 1000 to exactly 2000.

Which Lock Does synchronized Use?

Two pieces of code only exclude each other if they use the same lock. This table shows which lock each form uses.

CodeLock used
synchronized void m()this (the current object)
synchronized (this) { ... }this
static synchronized void m()ClassName.class
synchronized (ClassName.class) { ... }ClassName.class
synchronized (lockObject) { ... }lockObject
public class LockScope {
    private int count = 0;

    synchronized void instanceMethod() { count++; }   // locks "this"

    void sameAsInstanceMethod() {
        synchronized (this) { count++; }               // also locks "this"
    }

    public static void main(String[] args) throws InterruptedException {
        LockScope shared = new LockScope();
        LockScope other = new LockScope();

        // Both threads use the SAME object, so they share one lock
        Thread t1 = new Thread(() -> { for (int i = 0; i < 50_000; i++) shared.instanceMethod(); });
        Thread t2 = new Thread(() -> { for (int i = 0; i < 50_000; i++) shared.sameAsInstanceMethod(); });
        // This thread uses a DIFFERENT object, so it never waits for the others
        Thread t3 = new Thread(() -> { for (int i = 0; i < 50_000; i++) other.instanceMethod(); });

        t1.start(); t2.start(); t3.start();
        t1.join(); t2.join(); t3.join();

        System.out.println("shared.count = " + shared.count);
        System.out.println("other.count  = " + other.count);
    }
}

Output:

shared.count = 100000
other.count  = 50000

How it works:

  • instanceMethod() and the block synchronized (this) both lock shared, so t1 and t2 take turns and no update is lost.
  • t3 locks a different object, other. It never waits for t1 or t2, and it does not need to, because it changes a different count.
  • Locks belong to objects, not to code. The same method called on two different objects can run in two threads at the same time.

synchronized Locks Are Reentrant

A thread that already holds a lock can enter other code guarded by the same lock without blocking itself. This is called reentrancy.

public class Reentrant {
    private double balance = 100.0;

    synchronized void withdraw(double amount) {
        if (hasEnough(amount)) {          // calls another synchronized method
            balance -= amount;
            System.out.println("withdrew " + amount + ", balance " + balance);
        } else {
            System.out.println("declined " + amount + ", balance " + balance);
        }
    }

    synchronized boolean hasEnough(double amount) {
        return balance >= amount;         // same thread already holds the lock: no deadlock
    }

    public static void main(String[] args) {
        Reentrant account = new Reentrant();
        account.withdraw(30);
        account.withdraw(80);
    }
}

Output:

withdrew 30.0, balance 70.0
declined 80.0, balance 70.0

How it works:

  • withdraw() holds the account's lock and then calls hasEnough(), which needs the same lock.
  • Because the lock is reentrant, Java sees that the current thread already owns it and simply lets the thread in. Without reentrancy, the thread would wait for itself forever.

Thread Communication with wait() and notifyAll()

Synchronization also lets threads wait for a condition. Inside a synchronized method, wait() releases the lock and pauses the thread; notifyAll() wakes all threads waiting on the same object so they can re-check their condition.

import java.util.ArrayDeque;
import java.util.Queue;

public class WaitNotifyQueue {
    private final Queue<String> orders = new ArrayDeque<>();
    private final int capacity = 2;

    synchronized void put(String order) throws InterruptedException {
        while (orders.size() == capacity) {
            wait();               // queue full: release the lock and wait
        }
        orders.add(order);
        System.out.println("placed  " + order + "  queue=" + orders);
        notifyAll();              // wake threads waiting for an order
    }

    synchronized String take() throws InterruptedException {
        while (orders.isEmpty()) {
            wait();               // queue empty: release the lock and wait
        }
        String order = orders.remove();
        System.out.println("packed  " + order + "  queue=" + orders);
        notifyAll();              // wake threads waiting for free space
        return order;
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyQueue queue = new WaitNotifyQueue();

        Thread website = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    queue.put("order-" + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "website");

        Thread warehouse = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    queue.take();
                    Thread.sleep(100); // packing takes time
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "warehouse");

        website.start();
        warehouse.start();
        website.join();
        warehouse.join();
        System.out.println("all orders packed");
    }
}

Output (the exact interleaving can vary slightly between runs):

placed  order-1  queue=[order-1]
packed  order-1  queue=[]
placed  order-2  queue=[order-2]
placed  order-3  queue=[order-2, order-3]
packed  order-2  queue=[order-3]
placed  order-4  queue=[order-3, order-4]
packed  order-3  queue=[order-4]
placed  order-5  queue=[order-4, order-5]
packed  order-4  queue=[order-5]
packed  order-5  queue=[]
all orders packed

How it works:

  • The queue holds at most two orders. When it is full, website calls wait() in put() and sleeps until space is free.
  • warehouse takes an order and calls notifyAll(), which wakes the waiting website thread.
  • Both methods check their condition in a while loop, not an if. A woken thread must re-check, because another thread may have changed the queue first, and because threads can occasionally wake up without being notified.
  • Unlike Thread.sleep() (see Java Thread Sleep), wait() releases the lock, so the other thread can enter take() or put() meanwhile.

Note: wait(), notify() and notifyAll() must be called while holding the lock of the same object; otherwise they throw IllegalMonitorStateException. In real projects, a ready-made BlockingQueue such as ArrayBlockingQueue does all of this for you.


ReentrantLock: A Flexible Alternative to synchronized

The java.util.concurrent.locks.ReentrantLock class does the same job as synchronized, with extra features: you can try to get the lock with a time limit, interrupt a thread that is waiting for it, and request fair ordering.

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    private final ReentrantLock seatLock = new ReentrantLock();
    private int seatsLeft = 1;

    boolean book(String customer) throws InterruptedException {
        // Wait at most 200 ms for the lock instead of blocking forever
        if (!seatLock.tryLock(200, TimeUnit.MILLISECONDS)) {
            System.out.println(customer + ": system busy, please try again");
            return false;
        }
        try {
            if (seatsLeft == 0) {
                System.out.println(customer + ": sold out");
                return false;
            }
            Thread.sleep(500); // slow payment step while holding the lock
            seatsLeft--;
            System.out.println(customer + ": booked the last seat");
            return true;
        } finally {
            seatLock.unlock(); // always unlock in finally
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockDemo show = new LockDemo();
        Thread asha = new Thread(() -> {
            try { show.book("Asha"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        Thread ravi = new Thread(() -> {
            try { show.book("Ravi"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });

        asha.start();
        Thread.sleep(50); // Asha gets the lock first
        ravi.start();
        asha.join();
        ravi.join();

        System.out.println("seats left: " + show.seatsLeft);
    }
}

Output:

Ravi: system busy, please try again
Asha: booked the last seat
seats left: 0

How it works:

  • Asha gets the lock first and holds it for 500 ms during the slow payment step.
  • Ravi calls tryLock(200, TimeUnit.MILLISECONDS). He waits only 200 ms, then gets false and shows a friendly message instead of hanging.
  • unlock() is called in a finally block, so the lock is released even if the code inside throws an exception.
FeaturesynchronizedReentrantLock
Released automaticallyYes, when the block endsNo, call unlock() in finally
Try without waiting / with a timeoutNotryLock(), tryLock(time, unit)
Interruptible while waitingNolockInterruptibly()
Fair ordering optionNonew ReentrantLock(true)
ReentrantYesYes
Code sizeShortLonger

Use synchronized by default because it is shorter and cannot be forgotten to release. Switch to ReentrantLock when you need one of its extra features.


Real-World Example: Thread-Safe Bank Transfers

A transfer touches two accounts at once, so it must lock both. If one thread transfers A→B while another transfers B→A, and each locks its "from" account first, they can end up waiting for each other forever (a deadlock). Locking accounts in a fixed order avoids that.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class BankTransfer {

    static class Account {
        private final int id;
        private long balancePaise; // money stored as whole paise to avoid rounding errors

        Account(int id, long balancePaise) {
            this.id = id;
            this.balancePaise = balancePaise;
        }

        synchronized long balance() {
            return balancePaise;
        }
    }

    // Always lock the account with the smaller id first, so two opposite
    // transfers can never wait for each other forever (deadlock)
    static boolean transfer(Account from, Account to, long amount) {
        Account first = from.id < to.id ? from : to;
        Account second = from.id < to.id ? to : from;

        synchronized (first) {
            synchronized (second) {
                if (from.balancePaise < amount) {
                    return false; // not enough money: nothing changes
                }
                from.balancePaise -= amount;
                to.balancePaise += amount;
                return true;
            }
        }
    }

    static long totalMoney(List<Account> accounts) {
        long total = 0;
        for (Account a : accounts) {
            total += a.balance();
        }
        return total;
    }

    public static void main(String[] args) throws InterruptedException {
        List<Account> accounts = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            accounts.add(new Account(i, 100_000)); // Rs. 1,000.00 each
        }
        System.out.println("total before: " + totalMoney(accounts));

        int[] succeeded = new int[4]; // one slot per thread
        int[] declined = new int[4];
        Thread[] tellers = new Thread[4];
        for (int t = 0; t < tellers.length; t++) {
            int teller = t;
            tellers[t] = new Thread(() -> {
                ThreadLocalRandom random = ThreadLocalRandom.current();
                for (int i = 0; i < 25_000; i++) {
                    int fromIndex = random.nextInt(accounts.size());
                    // pick a different account for the receiver
                    int toIndex = (fromIndex + 1 + random.nextInt(accounts.size() - 1)) % accounts.size();
                    Account from = accounts.get(fromIndex);
                    Account to = accounts.get(toIndex);
                    if (transfer(from, to, random.nextLong(1, 20_000))) {
                        succeeded[teller]++;
                    } else {
                        declined[teller]++;
                    }
                }
            });
            tellers[t].start();
        }
        for (Thread teller : tellers) {
            teller.join();
        }

        int ok = 0, no = 0;
        for (int t = 0; t < tellers.length; t++) {
            ok += succeeded[t];
            no += declined[t];
        }
        System.out.println("total after : " + totalMoney(accounts));
        System.out.println("money preserved: " + (totalMoney(accounts) == 500_000));
        System.out.println("transfers attempted: " + (ok + no) + " (accepted + declined)");
        boolean noNegative = accounts.stream().allMatch(a -> a.balance() >= 0);
        System.out.println("no negative balances: " + noNegative);
    }
}

Output:

total before: 500000
total after : 500000
money preserved: true
transfers attempted: 100000 (accepted + declined)
no negative balances: true

How it works:

  1. Two locks per transfer. transfer() locks both accounts with nested synchronized blocks, so no other thread can change either balance in the middle of a transfer.
  2. Fixed lock order. The account with the smaller id is always locked first. Two transfers in opposite directions therefore request the locks in the same order and can never deadlock.
  3. Check and update under the lock. The balance check and both updates happen while holding both locks, so an account can never be overdrawn by two transfers that both "saw" enough money.
  4. Four tellers, 100,000 transfers. Each teller thread moves random amounts between random accounts. Each teller writes its counts into its own array slot, and main reads them after joining the threads.
  5. The proof. Money only moves between accounts, so the total must stay at 500,000 paise, and it does. No balance is negative. Remove the two synchronized lines and money preserved turns false on almost every run, because concurrent updates overwrite each other.

The next lesson, Java Thread Safety, looks at other ways to make code safe for many threads, such as immutable objects, atomic variables and concurrent collections.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Synchronization and get answers drawn from it.

Signed-in readers only.