Difference between volatile and transient keywords in Java
Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient.
Before getting into the differences, let us first understand what each of them actually means.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
The Volatile keyword is used to mark the JVM and thread to read its value from primary memory and not utilize cached value present in the thread stack. It is used in concurrent programming in java.
The Transient keyword is used with the instance variable to eliminate it from the serialization process. During serialization, the value of the transient field or variable is not saved.
The following table describes the differences:
Transient Volatile The Transient marked variable prevents it from being serialized. The Volatile marked variable follows happen-before relationship on visibility in multithreaded java program which reduces the risk of memory consistency errors. It gives control and flexibility over to exclude some object methods from serialization process. It prevents JVM from doing re-ordering which could compromise synchronization. During deserialization they are initialized with a default value. They are not initialized with a default value. It cannot be used with the static keyword as static variable do not belong to individual instance. During serialization, only object’s current state is concerned. It can be used with the static keyword. It cannot be used with the final keyword. Although JVM doesn’t complain about it but during deserialization one will face problem of reinitializing a variable. It can be used with the final keyword.