SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 5 / 19

Junior

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.

noyesexit or exceptionThread enters synchronizedMonitor free?BLOCKED, waitsTake monitor, run codeRelease monitornext thread sees changes

3 points to say:

  1. Instance methods lock this, static ones lock the Class.
  2. Lock on a private final Object.
  3. Always wait inside a while loop.

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.