Volatile vs Synchronized in Java

In this article, we will discuss volatile vs synchronized in Java.

First, we will define what is synchronized.

Synchronized Keyword

Synchronized is the keyword which is applied on blocks and methods but not on the classes and variables. When multiple threads are trying to access the same Java object so this situation leads to a data inconsistency problem. So in this situation, we should go for a synchronized keyword.

So we use synchronized keywords along with the name of the method declaration only so that if that method is accessing the Java object no other thread can access that object because synchronized methods hold a lock on that object. When it will do its processing and completes its task then the lock can be unlocked and can be used by other threads.

The biggest merit of using synchronized keywords is that we can overcome inconsistent state or can overcome inconsistency problems whereas the biggest demerit is that due to the lock to the object it may lead to performance issues.




Now, we will talk about volatile keywords.

Volatile Keyword

So basically the variable values are changed by different threads running concurrently and that value is changed i.e read and write on CPU cache which may lead to inconsistency. To avoid this problem we have a volatile modifier which is related to the visibility of the variable that is each variable value is read and write by threads running concurrently in the RAM itself instead of CPU cache.

Every change made by the threads shall take place in the local copy only so that the impact of the change will not take place in other threads. This will overcome the problem of inconsistency. Hence maintaining the separate copy for each thread may result in increasing the complexity of the program which is the demerit of this.





Volatile vs Synchronized

Synchronized Volatile
Synchronized keywords apply only to methods and blocks. Volatile apply only to variables. If we will try to apply volatile keywords along with the method then the compiler will show an error.
Synchronized keyword uses lock-based algorithms to lock those methods and blocks. Volatile implements a non-blocking algorithm that is more scalable.
Due to the acquisition and release of lock, the performance is slower in the synchronized keywords. Volatile is much better than synchronized in terms of performance.
Synchronized keyword follows locking approach due to which deadlocks and livelock may occur. Volatile does not follow this approach so it is free to deadlock and livelock.
Synchronized fields are part of compiler optimization. Volatile fields are not part of compiler optimization.


Both Synchronized and Volatile have their own merits and demerits therefore it is advised to use it in a very strict format (i.e. according to the specific requirements).

So, that’s all about volatile vs synchronized in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *