Wednesday, December 8, 2010

Java volatile vs. synchronized

If volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory.

volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

volatile:
- Get a global lock on the variable
- Update the one variable from main memory
- Write any change of the one variable back to main memory
- Release the lock

synchronized:
- Get a global lock on the monitor
- Update all shared variables that have been accessed from main memory
- Process some statements
- Write all shared variables that have been changed back to main memory
- Release the lock


reference: http://www.javaperformancetuning.com/news/qotm051.shtml

1 comment:

javin paul said...

Java Developers often mistake volatile as replacement of synchronized keyword which is not true. volatile keyword in Java
can guarantee visibility and ordering and prevent compiler to reorder code statement but as you mentioned can not guarantee atomicity which can only be achieved either by locking or by using Atomic classes from java.util.concurrent.atomic package. one more important thing to note is behavior of volatile keyword before and after java5. visibility and ordering guarantee is achieved by using happens-before relationship and every write in volatile variable happens before every read in volatile variable in java.Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire

Javin
How to use synchronized keyword in Java