There is no receptionist, it works more like a bathroom: Everyone locks the door upon entering, and people don't try to enter the bathroom if the door is locked:
while door is locked
wait
lock the door
do your business
unlock the door
That works provided that only a single person can succeed in locking the door (i.e. we check that we are alone in the bathroom before lowering our pants).
In IT terms, the JVM does something like this:
class Monitor {
AtomicReference owner = new AtomicReference();
void lock() {
do {
boolean alone = owner.compareAndSet(null, Thread.currentThread());
if (alone) {
return;
}
wait();
} while (true);
}
void unlock() {
if (owner.compareAndSet(Thread.currentThread(), null)) {
return;
} else {
throw new IllegalMonitorStateException();
}
}
}
AtomicReference.compareAndSet
delegates to a special hardware instruction that only updates a memory location if the previous value is as expected. The hardware ensures that this instruction is atomic, i.e. it is not possible for another instruction to change this memory location while this instruction executes. The particulars of the hardware instruction used depend on which hardware the JVM is running on.