Java Synchronization
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 write501, 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()issynchronized, so the read-add-write sequence can no longer be interrupted halfway by the other thread.getVisits()is alsosynchronized. 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
BLOCKEDstate 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 (
processedOrdersandauditLog) are insidesynchronized (lock). lockis aprivate final Object. Because no outside code can see it, no other code can accidentally hold it and slow this class down.mainreads the results inside the same lock after joining the threads, which is safe and consistent.
Note: Always lock on a
finalfield. 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:
nextInvoiceNumberisstatic, shared by the whole program.nextInvoice()isstatic 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.
| Code | Lock 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 blocksynchronized (this)both lockshared, sot1andt2take turns and no update is lost.t3locks a different object,other. It never waits fort1ort2, and it does not need to, because it changes a differentcount.- 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 callshasEnough(), 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,
websitecallswait()input()and sleeps until space is free. warehousetakes an order and callsnotifyAll(), which wakes the waitingwebsitethread.- Both methods check their condition in a
whileloop, not anif. 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 entertake()orput()meanwhile.
Note:
wait(),notify()andnotifyAll()must be called while holding the lock of the same object; otherwise they throwIllegalMonitorStateException. In real projects, a ready-madeBlockingQueuesuch asArrayBlockingQueuedoes 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 getsfalseand shows a friendly message instead of hanging. unlock()is called in afinallyblock, so the lock is released even if the code inside throws an exception.
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Released automatically | Yes, when the block ends | No, call unlock() in finally |
| Try without waiting / with a timeout | No | tryLock(), tryLock(time, unit) |
| Interruptible while waiting | No | lockInterruptibly() |
| Fair ordering option | No | new ReentrantLock(true) |
| Reentrant | Yes | Yes |
| Code size | Short | Longer |
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:
- Two locks per transfer.
transfer()locks both accounts with nestedsynchronizedblocks, so no other thread can change either balance in the middle of a transfer. - Fixed lock order. The account with the smaller
idis always locked first. Two transfers in opposite directions therefore request the locks in the same order and can never deadlock. - 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.
- 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
mainreads them after joining the threads. - 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
synchronizedlines andmoney preservedturnsfalseon 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.