Monday, 30 May 2011

Difference between synchronized and volatile



The main differences between synchronized and volatile are:
  • a primitive variable may be declared volatile whereas synchronized cannot be applied on the primitive types, but on some object or method or class.
  • Lock - Volatile deals with visibility, so if one thread modifies some variable, it will be known to other thread, so unlike a synchronized block we will never hold on to any lock; This is the big difference as synchronized offers mutual exclusion while volatile don't.
  • Attempting to synchronize on a null object will throw a NullPointerException, while  this is fine with volatile.
  • As synchronized offers mutual exclusion, it offers atomicity as well. But volatile doesn't mean atomic. (click on the link to see why)
Thanks

No comments:

Post a Comment