Card 01/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
One Thread at a Time, and the Object That Decides Which
A transfer reads a balance, checks it and writes it back. Making that one uninterruptible step is not something an atomic class can do, because it spans two fields and a condition.
synchronized marks a region that only one thread may be inside at a time. What enforces it is a lock, and every Java object has one.
class Account {
private long pence;
synchronized void withdraw(long amount) {
if (amount <= pence) {
pence -= amount;
}
}
}The keyword on line 4 is shorthand. A synchronized instance method locks this — the object the method was called on — for the whole of the body, and the long form says so out loud.
void withdraw(long amount) {
synchronized (this) {
if (amount <= pence) { pence -= amount; }
}
}So the question to ask of any synchronized is never whether it is there but which object it locked. Two threads are only excluded from each other if they are locking the same one, and nothing in the syntax makes that obvious.