Thread Synchronization in Java: synchronized and Monitors
Thread synchronization in Java means coordinating access of several threads to shared data so that only one thread works with it at any given moment. The main tool is the synchronized keyword: a thread entering a synchronized method or block acquires the object's monitor, and every other thread waits until it leaves. Besides mutual exclusion, synchronized in Java guarantees visibility: changes made inside the block are seen by the next thread that acquires the same monitor.
public class Counter {
private int count;
public synchronized void increment() { // one form: a synchronized method
count++;
}
public int get() {
synchronized (this) { // the other: a synchronized block
return count;
}
}
} Why you need this shows up in the simplest operation there is. Two threads each run count++ 100,000 times on a shared field. The total should be 200,000, but the program prints some smaller random number, say 113584, and throws no exception at all. The breakdown and the fix are in Race condition.
What Thread Synchronization Is and What a Race Condition Is
When two or more threads have access to one shared resource, you have to make sure the resource is used by only one thread at a time. The process that achieves this is called synchronization. Without it you get a race condition, and the result depends on how the scheduler happens to interleave the threads.
All threads of a process share common resources: the heap with its objects, static fields, open files. If one thread hasn't finished working with such a resource and the system switches to another thread that uses the same resource, the second thread sees the data in an intermediate, half-done state.
A race condition (data race) is a situation where several threads access the same data without synchronization and at least one of the accesses is a write. It doesn't have to be a call to the same method: a race also happens when one thread writes a field in one method and another thread reads it in a different method.
count++ is not an atomic operation
The shortest example of a race is a shared counter:
public class RaceExample {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("count = " + count);
}
} count = 113584 The number changes from run to run and is almost always below 200,000. Once in a while, especially on a single-core machine, you may get exactly 200,000, which doesn't make the code correct. The reason is that count++ is three steps: read the value, add one, write it back (read-modify-write). If both threads read 41, both write 42, and one increment is lost.
The fix is to run all three steps under one monitor:
public class RaceFixedExample {
private static int count = 0;
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
synchronized (lock) {
count++;
}
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("count = " + count);
}
} count = 200000 Now the result is the same on every run: while one thread executes count++, the other waits at the entrance to the block.
Example 1. Two threads withdrawing from one bank account
A more realistic example: two threads, Fred and Lucy, withdraw money from the same account. Between checking the balance and withdrawing, the thread sleeps for 500 ms, which makes the window for the race easy to see.
public class Account implements Runnable {
private int balance = 50;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance -= amount;
}
public void run() {
for (int x = 0; x < 5; x++) {
makeWithdrawal(10);
if (getBalance() < 0) {
System.out.println("account is overdrawn!");
}
}
}
private void makeWithdrawal(int amount) {
if (getBalance() >= amount) {
System.out.println(Thread.currentThread().getName()
+ " is going to withdraw");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return;
}
withdraw(amount);
System.out.println(Thread.currentThread().getName()
+ " completes the withdrawal. The balance is "
+ getBalance());
} else {
System.out.println("Not enough in account for "
+ Thread.currentThread().getName()
+ " to withdraw " + getBalance());
}
}
} public class AccountDangerExample {
public static void main(String[] args) {
Account account = new Account();
Thread one = new Thread(account);
Thread two = new Thread(account);
one.setName("Fred");
two.setName("Lucy");
one.start();
two.start();
}
} One possible output (shortened):
Fred is going to withdraw
Lucy is going to withdraw
Fred completes the withdrawal. The balance is 40
Lucy completes the withdrawal. The balance is 30
...
Fred is going to withdraw
Lucy is going to withdraw
Fred completes the withdrawal. The balance is 0
Lucy completes the withdrawal. The balance is -10
account is overdrawn!
Not enough in account for Fred to withdraw -10
... Both threads work with the same Account object, so they are in a race condition: both saw 10 on the account, both went to sleep, both withdrew 10, and the balance went negative.
To protect the data, we need to do two things:
- Declare the fields
privateso nobody can reach them bypassing the methods. - Synchronize the code that reads and modifies those fields.
Synchronized Method vs Synchronized Block
There are two ways to synchronize code in Java: declare the whole method with the synchronized modifier, or wrap the statements you need in a synchronized (object) { … } block. A synchronized instance method locks on the monitor of this; in a block you choose the lock object yourself.
- With synchronized methods. The method is declared with the
synchronizedkeyword:public synchronized void someMethod() { // the whole method runs under the monitor of this } - By wrapping the calls in a synchronized block:
synchronized (lock) { // statements that need to be synchronized }
A Java synchronized method is shorthand for a synchronized (this) block around the whole method body. A block is handier when only part of the method needs protection: the less code runs under the monitor, the less time other threads spend waiting in line.
Only methods and blocks can be synchronized, not variables or classes. There is no such thing as a "synchronized variable" in Java: what you protect is not the field but the code that accesses it, and all of that code has to lock on the same object.
Not every method in a class needs to be synchronized. Synchronization is needed where code reads or changes shared mutable data. Methods that work only with local variables or immutable fields don't need it, and an unnecessary synchronized just makes threads wait for each other for no benefit.
Besides synchronized, the java.util.concurrent package offers AtomicInteger (an atomic counter with no lock), ReentrantLock (a lock with tryLock() and timeouts) and thread-safe collections; they deserve lessons of their own. One thing to keep in mind already: even a thread-safe class doesn't make a sequence of its calls atomic, so "check, then act" on a thread-safe collection still needs a common lock.
The Monitor: How synchronized Works
Every object in Java has a monitor associated with it. A monitor is a mutual-exclusion lock tied to an object: synchronized acquires it on entry to the method or block and releases it on exit. When a thread asks for the lock, we say it enters the monitor.
Only one thread at a time can own a monitor. All other threads trying to enter a locked monitor are suspended until the first thread leaves it. They are said to be waiting for the monitor, and their state is BLOCKED (see BLOCKED vs WAITING in the thread states lesson).
The monitor is released on any exit from synchronized: after the last statement, on return, or because of an exception. You don't need to release it by hand, and you can't.
A thread that goes to sleep keeps the monitor: Thread.sleep() inside synchronized makes everyone else wait for the whole sleep (see What happens to a thread during sleep()).
A thread can hold several monitors at once by entering nested synchronized blocks. If two threads acquire the same monitors in different orders, they can end up waiting for each other forever. That's a deadlock, and the lesson Deadlock in Java shows how to avoid it.
Reentrancy
A thread that owns a monitor can enter it again. Java monitors are reentrant: a monitor counts how many times its owner has entered it and is released only when that count drops back to zero. That's why one synchronized method can call another synchronized method of the same object:
public class ReentrantExample {
public synchronized void outer() {
System.out.println("outer");
inner(); // we already own the monitor of this, so no waiting
}
public synchronized void inner() {
System.out.println("inner");
}
public static void main(String[] args) {
new ReentrantExample().outer();
}
} outer
inner Without reentrancy the thread would hang in inner(), waiting for a monitor it holds itself. The same rule lets a synchronized method in a subclass call super.method() that is also declared synchronized.
The bank account without a monitor and with one
Let's compare access to an object without synchronization and from synchronized code. Without synchronization, Lucy and Fred work with the account at the same time, and their steps get mixed up:
Here is how that can look step by step:
| Step | Lucy | Fred | Balance |
|---|---|---|---|
| 1 | Checks: 10 >= 10, OK to withdraw | — | 10 |
| 2 | Falls asleep before withdrawing | Checks: 10 >= 10, OK to withdraw | 10 |
| 3 | Withdraws 10 | Falls asleep before withdrawing | 0 |
| 4 | — | Withdraws 10 based on a stale check | -10 |
With synchronization, the check and the withdrawal run under the account's monitor, and Fred waits at the entrance:
When execution reaches the synchronized statement, the monitor of the account object is locked, and while it stays locked only one thread, the one that locked it (Lucy), has exclusive access to the block of code.
When the block finishes, the monitor of the account object is released and becomes available to other threads. Another thread then acquires it, and all the rest keep waiting for it to be released. Which thread gets the monitor next is not guaranteed.
Example 2. Synchronizing access to the account
Let's synchronize the method from the previous example so the threads can share the account correctly. The AccountDanger class uses Account from Example 1 only as a balance holder (its getBalance() and withdraw() methods):
public class AccountDanger implements Runnable {
private Account account = new Account();
public static void main(String[] args) {
AccountDanger accountDanger = new AccountDanger();
Thread one = new Thread(accountDanger);
Thread two = new Thread(accountDanger);
one.setName("Fred");
two.setName("Lucy");
one.start();
two.start();
}
public void run() {
for (int x = 0; x < 5; x++) {
makeWithdrawal(10);
if (account.getBalance() < 0) {
System.out.println("account is overdrawn!");
}
}
}
private synchronized void makeWithdrawal(int amt) {
if (account.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName()
+ " is going to withdraw");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return;
}
account.withdraw(amt);
System.out.println(Thread.currentThread().getName()
+ " completes the withdrawal. The balance is "
+ account.getBalance());
} else {
System.out.println("Not enough in account for "
+ Thread.currentThread().getName()
+ " to withdraw " + account.getBalance());
}
}
} One possible output (shortened):
Fred is going to withdraw
Fred completes the withdrawal. The balance is 40
Lucy is going to withdraw
Lucy completes the withdrawal. The balance is 30
...
Lucy completes the withdrawal. The balance is 0
Not enough in account for Fred to withdraw 0
... The "is going to withdraw" and "completes" lines now always come in pairs from the same thread, the balance never drops below zero, and "account is overdrawn!" is never printed. The order of names may differ: after leaving the method, Fred can easily grab the monitor again before Lucy does.
Notice which object the lock is on. makeWithdrawal() is a synchronized instance method, so the monitor is this, that is, the accountDanger object. The code works because both threads were created with the same accountDanger. But what's protected is not the account, it's "the way in through AccountDanger": if another class gets a reference to the same account and calls withdraw(), this monitor won't stop it. It's clearer to lock directly on the object you're protecting:
private void makeWithdrawal(int amt) {
synchronized (account) {
if (account.getBalance() >= amt) {
// the check and the withdrawal run under the account's monitor
account.withdraw(amt);
}
}
} This version only works if all code that changes this account is also synchronized on account. A monitor is an agreement between threads, not a padlock on a field.
sleep() under a monitor is for demos only
Thread.sleep(500) inside makeWithdrawal() is there so you can see the race in Example 1. In Example 2 it holds the monitor for half a second, and the other thread sits in BLOCKED the whole time: five withdrawals take about five seconds. In real code, slow operations (network, disk, pauses) go outside the synchronized block.
Which Object to Synchronize On
Lock on an object that never changes, is reachable by every thread working with the protected data, and is not reachable by outside code. The best default is private final Object lock = new Object(); this (for synchronized methods) and MyClass.class for static data are also acceptable.
| Lock object | When it fits | Gotchas |
|---|---|---|
private final Object lock | Almost always: protects instance fields | None: no outside code can lock on this monitor |
this / synchronized method | Simple classes that don't hand out a reference to themselves as a lock | Any code with a reference to the object can write synchronized (obj) and stall your methods |
MyClass.class | Static fields; same as static synchronized | The monitor is shared by the whole class and is public too |
String literal "lock" | Never | Literals are interned: another class using the same literal locks on the same object |
Integer, Long, Boolean | Never | Cached values (Integer from -128 to 127) are shared across the whole JVM; after a change the field points to a new object |
What's wrong with this code?
public class BrokenCounter {
private Integer count = 0;
public void increment() {
synchronized (count) {
count++;
}
}
} It looks like a protected counter, but the race is still there. For an Integer, count++ means count = Integer.valueOf(count + 1): after every increment the field refers to a different object. Two threads end up locking on different objects at different moments and don't get in each other's way. Since Java 16 the compiler warns about this mistake: attempt to synchronize on an instance of a value-based class (JEP 390). The fix is a separate private final Object lock, as in RaceFixedExample.
The general rule: a lock field must be final. If the reference to the lock object can be reassigned, sooner or later threads will end up on different monitors.
Synchronizing Static Methods
Static methods can be synchronized with the synchronized keyword too. They have no this, so the monitor is the class's Class object: one per class, shared by all instances.
Every class loaded in Java has a corresponding object of class java.lang.Class that represents it. The monitor of that object is what static methods synchronize on.
Example 3. Synchronizing static methods
public static synchronized int getCount() {
return count;
} And the equivalent code:
public static int getCount() {
synchronized (MyClass.class) {
return count;
}
} A static field changed by both static and instance methods has to be protected by one monitor, for example MyClass.class everywhere. Otherwise the static method locks on MyClass.class, the instance method on this, and they happily modify the field at the same time.
Which Calls Block Each Other
Two threads block each other only when they try to acquire the monitor of the same object. So the question "will these calls wait for each other?" always comes down to another one: which object is the monitor in each of them.
If a thread tries to enter a synchronized method while the monitor is taken, the thread blocks on the object's monitor: it moves to the BLOCKED state and waits in the entry queue until the monitor is released. Once it gets the monitor, the thread goes back to RUNNABLE.
| Thread 1 calls | Thread 2 calls | Do they block each other? | Why |
|---|---|---|---|
A non-static synchronized method of object a | The same or another non-static synchronized method of object a | Yes | One monitor: a |
A non-static synchronized method of object a | The same method of object b of the same class | No | Different monitors: a and b |
A static synchronized method of MyClass | Any static synchronized method of MyClass | Yes, always | Monitor MyClass.class |
A static synchronized method | A non-static synchronized method | No, never | MyClass.class and this are different objects |
synchronized (MyClass.class) in an instance method | A static synchronized method of MyClass | Yes | The same monitor is named explicitly |
synchronized (lock) | synchronized (lock) anywhere in the program | Yes | Blocks synchronized on the same object block each other |
A synchronized method of object a | A regular (non-synchronized) method of object a | No | Unsynchronized code doesn't check the monitor and runs in parallel |
The last row is a common source of bugs: a synchronized setter doesn't help if the getter for the same field is a plain method. Why such a getter can return not just an intermediate value but a stale one is explained in the next section.
synchronized and Visibility: happens-before
Releasing a monitor happens-before every subsequent acquisition of the same monitor (JLS 17.4.5). In practice this means that whatever a thread wrote inside synchronized is guaranteed to be visible to another thread that later enters synchronized on the same object. Without a shared monitor there is no such guarantee.
The reason lies in the hardware and the compiler. A CPU keeps data in its caches and registers, and the JIT compiler may reorder operations or skip re-reading a field from memory when the code has no synchronization. So a write by one thread may become visible to another thread late, or not at all. synchronized, volatile, Thread.join() and the classes in java.util.concurrent create happens-before relationships and thereby forbid those optimizations where it matters.
Hence the rule: if a field is changed under a monitor, it must also be read under the same monitor. That's why the get() method of Counter at the top of the lesson is synchronized too. Without it, a thread calling get() would be allowed to see an old value.
The volatile Modifier
The volatile modifier guarantees visibility and ordering, but not mutual exclusion: every read of a volatile field sees the latest write from any thread, and a write to it happens-before every later read. Reads and writes of a volatile variable are atomic (including long and double), but non-atomic operations such as count++ are not.
The typical use is a stop flag that one thread writes and another reads:
public class StopFlag {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long n = 0;
while (running) {
n++;
}
System.out.println("Stopped, iterations: " + n);
});
worker.start();
Thread.sleep(1000);
running = false;
worker.join();
}
} Stopped, iterations: 1873455620 The iteration count is different every time. Remove volatile and on HotSpot the program often never finishes: the JIT sees that running doesn't change inside the loop and reads it only once.
The counter from the start of the lesson, though, isn't saved by volatile. Declare private static volatile int count in RaceExample and the total is still below 200,000: each thread sees a fresh value, but the other thread manages to squeeze in between the read and the write. Compound operations need synchronized or AtomicInteger.
Thread Methods and the Monitor: What Is Released, What Is Kept
Of the thread-related methods, only wait() releases a monitor while waiting, and only the monitor of the object it was called on. sleep(), yield(), notify() and notifyAll() keep the monitor, and join() keeps every monitor except the monitor of the Thread object itself.
| Method | Class | What happens to the monitor |
|---|---|---|
wait(), wait(ms) | java.lang.Object | Releases the monitor of the object it was called on and reacquires it before returning. Other monitors held by the thread are not released |
notify(), notifyAll() | java.lang.Object | Keeps it: the awakened thread gets the monitor only after the notifying thread leaves synchronized |
sleep() | java.lang.Thread | Keeps all acquired monitors for the whole sleep |
yield() | java.lang.Thread | Keeps all monitors |
join() | java.lang.Thread | Keeps every monitor the waiting thread holds. The exception is the monitor of the Thread object join() was called on: for platform threads the method is implemented with wait() on that object and releases it while waiting |
Leaving synchronized (including via an exception) | — | Releases the monitor (taking the reentrancy count into account) |
The join() detail leads to a practical piece of advice from the Thread documentation: don't use Thread objects as locks and don't call wait()/notify() on them, because the JVM itself calls notifyAll() on a thread object when that thread terminates. How wait() and notify() let threads signal each other is a topic for a separate lesson on inter-thread communication.
synchronized and Virtual Threads
In Java 21–23, a virtual thread that blocks inside synchronized (sleeps, waits for I/O or calls wait()) gets pinned to its carrier thread and doesn't let go of it. Java 24 fixed this (JEP 491): virtual threads now acquire and release monitors independently of the carrier.
Why it mattered: there aren't many carrier threads, by default as many as there are CPU cores. If a few thousand virtual threads fall asleep under synchronized at once, they occupy every carrier, and the remaining virtual threads wait even though the CPU is idle. On Java 21 the workaround is to replace synchronized around long operations with ReentrantLock: while waiting for it, a virtual thread is unmounted from the carrier. On Java 24 and later you don't need to rewrite synchronized for the sake of virtual threads.
The semantics of synchronized are the same for virtual threads: mutual exclusion, reentrancy, happens-before. And "don't hold a monitor during slow operations" still applies in every version: a busy monitor makes other threads wait, however lightweight they are.
Frequently Asked Questions
Can a constructor, a field or a class be declared synchronized?
No. The synchronized modifier is allowed only on methods and as a block; on a constructor, field or class the compiler reports "modifier synchronized not allowed here". A constructor doesn't need it anyway: until it finishes, only the creating thread sees the reference to the new object (unless you leak this yourself). Inside a constructor you can still use a synchronized (lock) block if it touches shared data.
What happens to the monitor if an exception is thrown inside synchronized?
The monitor is released automatically: the JVM lets go of it on any exit from the block, including an exception. That's the difference from ReentrantLock, where you have to call unlock() in finally yourself. The data, however, may be left half-updated, for example money taken from one account but not yet added to the other, and the next thread will see it that way.
Do threads get the monitor in first-come, first-served order?
No, synchronized doesn't guarantee fairness. A thread that just left the block can immediately grab the monitor again, while a thread that has been waiting for a long time keeps waiting. You can see it in Example 2, where one thread sometimes makes several withdrawals in a row. If order matters, use new ReentrantLock(true), a fair lock that is slower.
Does synchronized slow a program down much?
Acquiring an uncontended monitor is cheap, on the order of tens of nanoseconds. Contention is what costs: when threads constantly wait for each other, they sit idle, and a multithreaded program may run no faster than a single-threaded one. So the goal is not to remove synchronized but to keep as little code under it as possible. Biased locking, an optimization that sped up monitors used by a single thread, is disabled by default since Java 15 (JEP 374), so old Java 8 benchmarks don't apply to current versions.
Comments