Difference between Volatile and synchronized Keyword is very popular java question asked in Multithreading and concurrency interviews. Here are few differences listed down :
1) Volatile in java is a keyword which is used in variable declaration only and cannot be used with method. We will get compilation error if using volatile with method.
Syntax to use volatile with variable:
volatile Boolean flag ;
While synchronization keyword is used in method declaration or can be used to create synchronization blocks. We will get compilation error if we define variables as synchronized
How to use Synchronized method and Synchronized block
Synchronized method:
synchronized void executeMethod(){
//write code inside synchronized method
}
Synchronized block:
void executeMethod(){
synchronized (this)
{
//write code inside synchronized block
}
}
2) Volatile variables read values from main memory and not from cached data so volatile variables are not cached whereas variables defined inside synchronized block are cached.
3) Volatile variables are lock free which means that it does require any lock on variable or object whereas synchronized requires lock on method or block .
4) Volatile variable can be null whereas we will get NullPointerException in case we use null object.
5) As volatile never acquires any kind of lock ,so it will never create deadlock in program. But in case of synchronized we might end up creating deadlock if synchronization is not done properly.
6) Synchronized keyword may cause performance issue as one thread wait for another thread to release lock on shared object whereas volatile variable is lock free and hence is not much expensive in terms of performance.
7) Using synchronization thread can be blocked when waiting for other thread to release lock but not in the case of volatile keyword.
8) Volatile keyword is suitable When there is an independent value to be share among multiple threads like counter and flag.
Whereas synchronization is used in the scenario where we are using multiple variables very frequently and these variables are performing some calculation.