Video in progress
What does the synchronized keyword actually do?
It acquires the object's monitor: only one thread at a time can enter the code guarded by that monitor. On top of that, changes made before leaving the block become visible to the next thread that enters.
📖 Answer
synchronized does two things, and people often forget the second one in interviews:
- Mutual exclusion: other threads wait (in the BLOCKED state).
- Visibility: there is a happens-before relationship between releasing the monitor and later acquiring it, so the next thread doesn't see a stale value.
class Wallet {
private long balance;
public synchronized void deposit(long amount) {
balance += amount;
}
public void withdraw(long amount) {
synchronized (this) { // the block form: the same monitor
if (balance < amount) throw new IllegalStateException("mablag' yetarli emas");
balance -= amount;
}
}
}
synchronized is reentrant: if a thread that holds a monitor calls another method guarded by the same monitor, it doesn't block itself.
Important: the protection only works if the same monitor is used everywhere. If you read balance with synchronized in one place and without it in another, the protection has a hole.
Sign up to mark studied questions and save your progress.