What is Volatile keyword in Java?

What is Volatile keyword in Java?

What is Volatile keyword in Java?

What is Volatile keyword in Java?
  • Volatile is the modifier applies only to variables and we can’t apply anywhere else.
  • If the value of a variable keeps on changing by multiple threads then there may be a chance of data inconsistency problem. We can solve this problem by using the volatile modifier.
  • If a variable declares as volatile then 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 remaining threads.
  • The main advantage of volatile keyword is we can overcome data inconsistency problem but the main disadvantage of volatile keyword is creating and maintaining a separate copy for every thread increases the complexity of programming and creates performance problem hence if there is no specific requirement it is never recommended to use volatile keyword and it is almost deprecated keyword.
  • Declaring a volatile Java variable means:
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”;
  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
  • Final variable means the value never changes whereas volatile variable means the value keeps on changing hence volatile-final is an illegal combination of variables.
  • Note that volatile should not be confused with the static modifier. static variables are class members that are shared among all objects. There is only one copy of them in main memory.

Leave a Reply

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

*