MY mENU


Saturday 19 January 2013

Transient and Volatile Variable in JAVA


Transient variable: the class level variable that has transient keyword in its definition is called transient variable. Local variable cannot be declared as transient. It leads to CE: illeagal start expression.
We declare variable as transient to tell to JVM that we do not want to store variable value in a file in object serialization. Since local variable is not part object, declaring it as transient is illegal. For more details on object serialization and transient variable refer IOStreams concept.

Class example {
Static transient int x=10;
Transient int y=20;
}

Volatile variable: the class level variable that has volatile keyword in its definition is called volatile variable. . Local variable cannot be declared as volatile. It leads to CE: illeagal start expression.
We declare variable as volatile to tell to JVM that we do not want to modify variable value concurrently by multiple threads. If we declare variable as volatile multiple thread are allowed to change its value in sequence one after one.
Class example {
Static volatile int x=10;
Volatile int y=20;
}