Repaso
EspaƱol
Java CoreIntermediateJV-26

What is the difference between synchronized and volatile?

Options

  1. They are identical in effect, only the keyword is different
  2. synchronized locks and shares writes; volatile only shares (Correct option)
  3. volatile locks the whole object; synchronized does not lock
  4. volatile can only be applied to methods and never to fields

Answer

synchronized gives mutual exclusion plus visibility; volatile only guarantees that reads see the latest write (no atomicity for compound actions)

Why

synchronized makes a block run by one thread at a time (mutual exclusion) and also makes changes visible to the next thread that enters.

volatile on a field only guarantees visibility: when one thread writes, others immediately see the new value (no stale cached copy). It does NOT make count++ safe, because that is three steps: read, add, write.

Use volatile for simple flags (running = false), synchronized or AtomicInteger for counters and compound actions.

Remember

volatile = visibility only. synchronized = lock + visibility.

Key terms

Practice this question in Repaso