Difference between transient vs volatile variable or modifier in Java

Transient vs volatile modifier in Java
What is difference between transient and volatile variable or modifier in Java is one of the most common Serialization Interview Question in Java. Though volatile variables are not related to Serialization at all, this question is mostly asked in conjunction with other Serialization question. Both transient and volatile modifiers are completely different to each other. In fact this question is as popular as Serializable vs Externalizable in Java. Main difference between transient vs volatile variable is that transient variables are not serialized during Serialization process in Java while volatile variables are used to provide alternative synchronization in Java. By using volatile keyword or modifier on fields, signals compiler that this variable is accessed by multiple thread and any reordering or optimization by compiler should be avoided. In this Java article we will see some difference between transient and volatile variable by learning each of them and when to use transient and volatile variable in Java.

Difference between transient vs volatile variables Java
Let's see difference between transient and volatile variables in point format for easy understanding and revision:

1. By making a variable or field transient in a Class prevents it from being serialized in Java. Along with static variables, transient variables are not serialized during Serialization and they are initialized with their default value during deserialization process e.g. an int transient variable is initialized with zero during deserialization in Java.

2. On the other hand volatilevariables are used in Concurrent programming in Java. When we declare a variable volatile, every thread reads its value from main memory and doesn’t used cached value available in every thread stack. Volatile variable also prevents compiler from doing reordering which can compromise synchronization. Many Java programmers though know about volatile variables they are not sure where to use volatile modifier in Java. One of the popular examples of using volatile variable is implementing double checked locking in Singleton, where Singleton instance of class is declared volatile in Java.

That's all on difference between transient and volatile variables in Java. Transientvariables are used to prevent serialization or a field while volatile variables are used to prevent reordering and avoid reading cached value of field in multithreaded Java program. Only similarity between transientand volatilekeyword is that they are only applicable to field or properties of class. You cannot use transient or volatile keyword during class or method declaration in Java.


Post a Comment