What is the difference between synchronized and volatile?
Options
- They are identical in effect, only the keyword is different
synchronizedlocks and shares writes;volatileonly shares (Correct option)volatilelocks the whole object;synchronizeddoes not lockvolatilecan 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.