Skip to lesson

synchronized methods

A synchronized method lets only one thread at a time run it on a given object. Other threads wait at the door, so a read-modify-write or a check-then-act inside the method runs as one atomic action.

Every object has a built-in lock (monitor)

synchronized makes a method or block run by only one thread at a time for the same lock object, which prevents race conditions on shared data.

Every Java object has a built-in lock, also called its monitor or intrinsic lock. Only one thread can hold a given object's lock at a time. While one thread holds it, any other thread that asks for the same lock must wait.

An object has one lock, drawn as one key. Thread A holds the key and runs the synchronized block that changes the balance. Thread B also wants the key but it is BLOCKED and must wait until A leaves the block and gives the key back.

Example 1 · A thread waits, BLOCKED, for the lock

BlockedStateDemo.javaJava
class Locker {    synchronized void useFor(int ms) {        try {            Thread.sleep(ms);          // holds the lock of this Locker while sleeping        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
public class BlockedStateDemo {    public static void main(String[] args) throws InterruptedException {        Locker locker = new Locker();        Thread first = new Thread(() -> locker.useFor(200), "first");        Thread second = new Thread(() -> locker.useFor(10), "second");
        first.start();        Thread.sleep(50);              // let "first" take the lock        second.start();        Thread.sleep(50);              // "second" is now trying to enter
        System.out.println("first:  " + first.getState());        System.out.println("second: " + second.getState());
        first.join();        second.join();        System.out.println("second after join: " + second.getState());    }}
Sample output
first:  TIMED_WAITING
second: BLOCKED
second after join: TERMINATED

What this code does

  • first holds the lock of locker while it sleeps (TIMED_WAITING). second calls a synchronized method on the same object, so it waits in the BLOCKED state until first returns.
  • The pauses in main make this order very likely, but it is still timing, so the output is a sample. Note that sleep does not release the lock: the thread keeps the key while it waits.

A thread waiting for a lock is in the BLOCKED state, one of the thread states from the Thread Basics module. It does no work and uses no CPU until the lock is free; then it takes the lock and carries on. Think of a single-key washroom at a petrol pump. Whoever has the key goes in; everyone else queues until the key comes back.

One thread at a time inside a synchronized method

A synchronized method is a method marked with the synchronized keyword. Before its body runs, the thread takes the lock of this, the object the method was called on. When the method ends, normally or by throwing an exception, the thread releases the lock.

Example 2 · Two counters serve one queue, one at a time

OneAtATimeDemo.javaJava
class ServiceWindow {    synchronized void serve(String counter, String student) {        System.out.println(counter + " starts: " + student);        try {            Thread.sleep(50);          // filling the fee receipt        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }        System.out.println(counter + " done:   " + student);    }}
public class OneAtATimeDemo {    public static void main(String[] args) throws InterruptedException {        ServiceWindow window = new ServiceWindow();        Thread c1 = new Thread(() -> window.serve("counter-1", "Asha"), "counter-1");        Thread c2 = new Thread(() -> window.serve("counter-2", "Ravi"), "counter-2");        c1.start();        Thread.sleep(10);              // counter-1 usually gets the lock first        c2.start();        c1.join();        c2.join();    }}
Sample output
counter-1 starts: Asha
counter-1 done:   Asha
counter-2 starts: Ravi
counter-2 done:   Ravi

What this code does

  • serve is synchronized, so once counter-1 is inside, counter-2 waits for the lock of window. Each "starts" line is always followed by its own "done" line; the two services never mix.
  • Which counter goes first depends on which thread asks for the lock first. The short pause in main makes counter-1 first on almost every run. Without synchronized you would see both "starts" lines before both "done" lines.

All synchronized methods of one object share that one lock. So while one thread is inside deposit, no other thread can enter deposit or withdraw on the same object. A method without synchronized does not ask for the lock, so it can still run at any time. Two different objects have two different locks. Threads working on different BankAccount objects never wait for each other. To check who holds a lock, Thread.holdsLock(obj) returns true when the current thread holds the lock of obj.

Order of execution

Two threads, one lock

Put the steps in order. Thread A gets to the account first.

Releasing the lock also makes the changes made inside the method visible to the next thread that takes the same lock. The Visibility module explains this rule, called happens-before.

Fixing the shared counter

Mutual exclusion means that only one thread at a time can run a piece of code. Marking increment() as synchronized gives the counter mutual exclusion, so the read, the add and the write happen with no other thread in between.

Example 3 · The shared counter, fixed

SyncCounterDemo.javaJava
class Counter {    private int count = 0;
    synchronized void increment() {        count++;                       // read, add, write with no other thread in between    }
    synchronized int get() {        return count;    }}
public class SyncCounterDemo {    public static void main(String[] args) throws InterruptedException {        Counter counter = new Counter();        Runnable task = () -> {            for (int i = 0; i < 1_000_000; i++) {                counter.increment();            }        };        Thread a = new Thread(task, "adder-1");        Thread b = new Thread(task, "adder-2");        a.start();        b.start();        a.join();        b.join();        System.out.println("Expected: 2000000");        System.out.println("Actual:   " + counter.get());    }}
Output
Expected: 2000000
Actual:   2000000

What this code does

  • This is the counter from the first lesson with one word added. Both threads call increment() on the same object, so they take turns on its lock, and no update is lost. The total is 2,000,000 on every run.
  • count is now private, so no code outside the class can skip the lock. get() is synchronized too, so a reader always sees a value written under the same lock.

Example 4 · Mistake: one method forgot synchronized

HalfLockedDemo.javaJava
class Stock {    private int units = 0;
    synchronized void add() {        units++;    }
    void remove() {                    // missing synchronized        units--;    }
    synchronized int get() {        return units;    }}
public class HalfLockedDemo {    public static void main(String[] args) throws InterruptedException {        Stock stock = new Stock();        Thread supplier = new Thread(() -> {            for (int i = 0; i < 1_000_000; i++) {                stock.add();            }        }, "supplier");        Thread buyer = new Thread(() -> {            for (int i = 0; i < 1_000_000; i++) {                stock.remove();            }        }, "buyer");        supplier.start();        buyer.start();        supplier.join();        buyer.join();        System.out.println("Units left (should be 0): " + stock.get());    }}
Sample output
Units left (should be 0): -41587

What this code does

  • remove() never asks for the lock, so it runs in the middle of add() and the two read-modify-writes overwrite each other. The result is a different wrong number on each run, positive or negative.
  • The fix is to add synchronized to remove() as well. A lock protects data only if every piece of code that touches the data takes it.

The rule is strict: every method that reads or writes the shared field must use the same lock. If increment() is synchronized but decrement() is not, a thread in decrement() can still run in the middle of an increment(), and updates are lost again.

Predict the output

Predict the output

Both programs use synchronized, so they always print the same lines.

Round 1 of 2

Two threads each add 1 a thousand times to a synchronized counter.

public class SyncCount {
private int count = 0;
synchronized void increment() {
count++;
}
synchronized int get() {
return count;
}
public static void main(String[] args) throws InterruptedException {
SyncCount c = new SyncCount();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
c.increment();
}
};
Thread a = new Thread(task);
Thread b = new Thread(task);
a.start();
b.start();
a.join();
b.join();
System.out.println(c.get());
}
}

Static synchronized methods lock the class

A static synchronized method locks the class itself, not an object. Every class has one Class object, such as TicketCounter.class, and that object's lock is used. So all threads calling static synchronized methods of the class take turns, no matter which objects they use.

Example 5 · A static field needs the class lock

StaticLockDemo.javaJava
class TicketCounter {    static int totalSold = 0;          // shared by every TicketCounter    static int totalSoldSafe = 0;
    synchronized void sellUnsafe() {   // locks THIS counter only        totalSold++;    }
    static synchronized void sellSafe() {   // locks TicketCounter.class        totalSoldSafe++;    }}
public class StaticLockDemo {    public static void main(String[] args) throws InterruptedException {        TicketCounter platform1 = new TicketCounter();        TicketCounter platform2 = new TicketCounter();        Thread t1 = new Thread(() -> {            for (int i = 0; i < 1_000_000; i++) {                platform1.sellUnsafe();                TicketCounter.sellSafe();            }        }, "platform-1");        Thread t2 = new Thread(() -> {            for (int i = 0; i < 1_000_000; i++) {                platform2.sellUnsafe();                TicketCounter.sellSafe();            }        }, "platform-2");        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println("Instance lock: " + TicketCounter.totalSold + " (should be 2000000)");        System.out.println("Class lock:    " + TicketCounter.totalSoldSafe);    }}
Sample output
Instance lock: 1873034 (should be 2000000)
Class lock:    2000000

What this code does

  • platform1 and platform2 are different objects, so sellUnsafe() uses two different locks and the two threads never wait for each other. The static field still loses updates; that number changes from run to run.
  • sellSafe() is static synchronized, so both threads use the one lock of TicketCounter.class and the second total is always 2,000,000.

This matters for static fields. A static field is shared by every object, so it needs a lock that every object shares: the class lock. An instance synchronized method only locks its own object, which does not protect a static field. An instance synchronized method and a static synchronized method of the same class use different locks, so they do not block each other.

Next step

Check your understanding

12 quick questions