What are transient and volatile modifiers?
When serializable interface is declared, the compiler knows that the object has to be handled so as to be able to serialize it. However, if you declare a variable in an object as transient, then it doesn’t get serialized.
VolatileSpecifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all.
Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
What are transient and volatile modifiers?
Volatile is a access modifier that informs to the compiler that the variable with this modifier can be changed unexpectedly by other elements of the program. In multithreading environment, one or more threads can share the same instance variables. Each thread can have its own copy of volatile variable. The real copy or the master copy of the variable is updated at times.
The transient access modifier is used at the time of object serialization in order not to serialize the instance variable value.
In the following code snippet, the content of the variable “nopersist” would not be saved. The content of the variable “number” would be saved.
class SampleSerialize
{
transient int nopersist; // will not persist
int number; // will persist
……
……
}