synchronized blocks and which object is the lock
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A synchronized block locks one chosen object for just a few lines of code. The code inside is protected only against threads that lock the same object, so picking the lock object is the real decision.
synchronized (this) versus a private final lock object
A lock, or monitor, is held by one thread at a time; every Java object has one, and synchronized code must get it before running.
A synchronized block is written synchronized (lockObject) { ... }. The thread takes the lock of lockObject before the braces and releases it after them.
Many teams prefer a private final lock object: private final Object lock = new Object();. The code below uses one.
Example 1 · A counter guarded by a private lock
class Counter { private final Object lock = new Object(); // only this class can use it private int count = 0;
void increment() { synchronized (lock) { count++; } }
int get() { synchronized (lock) { return count; } }}
public class PrivateLockCounterDemo { 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("Count: " + counter.get()); }}Count: 2000000
What this code does
- Both methods lock the same
lockobject, socount++and the read never overlap with another thread's update. The result is right on every run. - This behaves like synchronized methods, but the lock is hidden inside the class. Code outside cannot take it, so it cannot accidentally slow down or block the counter.
Example 2 · Outside code holding the lock of this
class ThisLockedAccount { private int balance;
synchronized void deposit(int amount) { // locks this balance += amount; }}
class PrivateLockAccount { private final Object lock = new Object(); private int balance;
void deposit(int amount) { synchronized (lock) { // locks a private object balance += amount; } }}
public class OutsiderLockDemo { static long waitForDeposit(Object account, Runnable deposit) throws InterruptedException { Thread outsider = new Thread(() -> { synchronized (account) { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }, "outsider"); outsider.start(); Thread.sleep(50); // the outsider now holds the account's lock long start = System.nanoTime(); deposit.run(); long waitedMs = (System.nanoTime() - start) / 1_000_000; outsider.join(); return waitedMs; }
public static void main(String[] args) throws InterruptedException { ThisLockedAccount a = new ThisLockedAccount(); long w1 = waitForDeposit(a, () -> a.deposit(100)); System.out.println("Lock on this, deposit had to wait: " + (w1 >= 100));
PrivateLockAccount b = new PrivateLockAccount(); long w2 = waitForDeposit(b, () -> b.deposit(100)); System.out.println("Private lock, deposit had to wait: " + (w2 >= 100)); }}Lock on this, deposit had to wait: true Private lock, deposit had to wait: false
What this code does
- The
outsiderthread locks the account object itself and sleeps.ThisLockedAccount.depositneeds that same lock, so it waits about 150 ms.PrivateLockAccount.depositneeds a different, hidden lock, so it runs at once. - The result depends on timing (the 50 ms pause in
main), so it is a sample, but it comes out this way on almost every run. With a private lock, no outside code can hold up your class by accident.
It is private, so no code outside the class can take it and hold up your methods. It is final, so it can never be swapped for a different object halfway through the program.
Writing synchronized (this) { ... } uses the same lock as a synchronized method of that object. With this as the lock, any outside code that does synchronized (account) competes with the account's own methods. With a private lock, only the class itself decides who waits. A synchronized block releases its lock even if an exception leaves it.
Two threads locking different objects protect nothing
A lock protects shared data only when every thread uses the same lock object for that data.
This bug hides well, because the code looks locked.
Example 3 · Mistake: each worker brings its own lock
class Scoreboard { int runs = 0;}
class Batter implements Runnable { private final Object lock = new Object(); // a different lock for every Batter private final Scoreboard board;
Batter(Scoreboard board) { this.board = board; }
@Override public void run() { for (int i = 0; i < 1_000_000; i++) { synchronized (lock) { board.runs++; } } }}
public class WrongLockDemo { public static void main(String[] args) throws InterruptedException { Scoreboard board = new Scoreboard(); Thread rohit = new Thread(new Batter(board), "rohit"); Thread virat = new Thread(new Batter(board), "virat"); rohit.start(); virat.start(); rohit.join(); virat.join(); System.out.println("Runs: " + board.runs + " (should be 2000000)"); }}Runs: 1689243 (should be 2000000)
What this code does
- Each
Batterobject has its ownlock, sorohitandviratlock two different objects and never wait for each other. The sharedboard.runsstill loses updates, and the number changes from run to run. - The code looks protected, which is why this bug survives code reviews. Ask one question: do all threads that touch this data lock the same object?
Example 4 · The fix: the lock lives with the data
class Scoreboard { private final Object lock = new Object(); // one lock, inside the shared object private int runs = 0;
void addRun() { synchronized (lock) { runs++; } }
int runs() { synchronized (lock) { return runs; } }}
class Batter implements Runnable { private final Scoreboard board;
Batter(Scoreboard board) { this.board = board; }
@Override public void run() { for (int i = 0; i < 1_000_000; i++) { board.addRun(); } }}
public class RightLockDemo { public static void main(String[] args) throws InterruptedException { Scoreboard board = new Scoreboard(); Thread rohit = new Thread(new Batter(board), "rohit"); Thread virat = new Thread(new Batter(board), "virat"); rohit.start(); virat.start(); rohit.join(); virat.join(); System.out.println("Runs: " + board.runs()); }}Runs: 2000000
What this code does
- There is one
Scoreboardand therefore onelock. Both batters go throughaddRun(), so both use the same lock and the total is right on every run. runsis now private, so aBattercannot change it without the lock even by mistake. Keeping the lock inside the class that owns the data is the habit that prevents this whole family of bugs.
Common causes are a lock field inside each worker object instead of inside the shared data, and synchronized (new Object()), which makes a fresh lock on every call. If thread A locks object X and thread B locks object Y, they never wait for each other, and the data is as unsafe as with no lock at all.
The safest habit is to keep the lock next to the data it protects, inside the same class. Then every caller goes through that class's methods and automatically uses the right lock.
Never lock on String literals or boxed Integers
String literals are shared across the whole JVM: every "lock" written anywhere in any class is the very same object. If two unrelated classes both lock on "lock", they block each other for no reason, and can even get stuck waiting for each other.
class Hostel { static final String LOCK = "lock";}
class Library { static final String LOCK = "lock";}
public class SameStringDemo { public static void main(String[] args) { System.out.println(Hostel.LOCK == Library.LOCK); }}true
Boxed values such as Integer are a different trap. seats-- on an Integer makes a new Integer object, so the lock object changes after every update and threads end up holding different locks. Small values from -128 to 127 are also cached and shared JVM-wide. Since Java 16, javac warns: "attempt to synchronize on an instance of a value-based class".
Example 5 · Mistake: locking on a boxed Integer
public class IntegerLockDemo { static Integer seatsLeft = 1_000_000;
public static void main(String[] args) throws InterruptedException { Runnable booker = () -> { for (int i = 0; i < 500_000; i++) { synchronized (seatsLeft) { // the lock object changes below seatsLeft--; // makes a NEW Integer object } } }; Thread a = new Thread(booker, "booker-1"); Thread b = new Thread(booker, "booker-2"); a.start(); b.start(); a.join(); b.join(); System.out.println("Seats left: " + seatsLeft + " (should be 0)"); }}Seats left: 148120 (should be 0)
What this code does
seatsLeft--unboxes the value, subtracts and boxes the result into a newInteger. The next thread then locks that new object while another thread may still hold the old one, so the threads often use different locks and updates are lost.javacwarns about this line:attempt to synchronize on an instance of a value-based class. The fix is a separateprivate static final Object lock = new Object();and anintfield.
Lock on an object you created yourself for that purpose, such as a private final Object lock.
Reentrancy: a thread can take a lock it already holds
Java's built-in locks are reentrant: a thread that already holds a lock can take it again without waiting for itself. The JVM keeps a count, and the lock is truly released only when the thread leaves the last block or method that took it.
Example 6 · Reentrancy: a synchronized method calls another
class TicketDesk { private int sold = 0; private int fees = 0;
synchronized void sell(int fee) { sold++; addFee(fee); // needs the same lock, already held System.out.println("sell: holds lock? " + Thread.holdsLock(this)); }
synchronized void addFee(int fee) { fees += fee; System.out.println("addFee: holds lock? " + Thread.holdsLock(this)); }
synchronized String report() { return "Sold: " + sold + ", fees: Rs " + fees; }}
public class ReentrancyDemo { public static void main(String[] args) throws InterruptedException { TicketDesk desk = new TicketDesk(); Thread clerk = new Thread(() -> desk.sell(30), "clerk"); clerk.start(); clerk.join(); System.out.println(desk.report()); System.out.println("main holds lock? " + Thread.holdsLock(desk)); }}addFee: holds lock? true sell: holds lock? true Sold: 1, fees: Rs 30 main holds lock? false
What this code does
- The
clerkthread entersselland takes the lock ofdesk. Inside,addFeeneeds the same lock; because the lock is reentrant, the thread simply enters again instead of waiting for itself. - The JVM counts the two entries. After
addFeereturns the thread still holds the lock (the second line), and only whensellreturns is it released, somaincan then callreport().
This is what lets one synchronized method call another synchronized method on the same object, or a subclass's synchronized method call super's. Without reentrancy the thread would wait forever for a lock it holds itself. Reentrancy applies only to the same thread. A different thread still waits until the count drops to zero.
Next step
Check your understanding
12 quick questions