Volatile and Synchronized keywords are mainly used with threads.
- Synchronized modifier
When multiple threads are trying to operate simultaneously on the same java object, there may be chance of data inconsistency problem. To overcome this kind of a problem we should go for synchronized keyword.
👉Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes.
If a method or block declares as synchronized then at a time only one thread is allowed to execute that method or block on the given object, So the data inconsistency problem will resolved. The main disadvantage of this keyword is it increases the waiting time of the thread and creates performance problems.
- Volatile modifier
If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem.
👉It is a modifier applicable only for variables, and we cannot apply it anywhere else.
If a variable is declared as volatile as for every thread JVM will create a separate local copy. Every modification performed by the thread will take place in the local copy so that there is no effect on the remaining threads.
Overcoming the data inconsistency problem is the advantage and the volatile keyword is creating and maintaining a seperate copy for every thread increases complexity of the program and create performance issue. Hence if there are no specific requirement it is never recommended to use volatile keywords.
Let's look at the summary of the today's blog post,
That's it for today, Hope you got the idea of Volatile and Synchronized keywords in Java.
Hope to see you guys with a new blog post soon.
Thank You.
Comments
Post a Comment