How does synchronized work, and which object does it lock?
Short answer
Every Java object has a monitor (lock). synchronized takes the lock on entry and releases it on exit, even on an exception. It gives one thread at a time and visibility of changes.
3 points to say:
- Instance methods lock
this, static ones lock theClass. - Lock on a
private final Object. - Always
waitinside awhileloop.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.