ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

Difference between synchronized and volatile keyword in Java

Difference between volatile and synchronized is another popular core Java question asked in multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

 

1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods.

 

2. Synchronized obtains and releases lock on monitor’s java volatile keyword doesn't require that.

 

3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java.

 

4. Synchronized method affects performance more than volatile keyword in Java.

 

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory  and "main" memory  while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

 

6. You can not synchronize on null object but your volatile variable in java could be null.

 

7. From Java 5 Writing into 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

Related Posts Plugin for WordPress, Blogger...
Flag Counter