Transient
Object serialization is one of the important concepts in java programming language. It is the process of saving an object’s state to a persistent storage in the form of bytes, as well as the process of building the same object from those bytes in future. Java Serialization API offers standard methods to developers to make the object state persistent , which is fairly small and easy to use.
Object serialization converts all the variable into the persistent. But in many cases you may not want to persist certain variables, for example, if there is a variable which is derived from others fields, which is purely done programmatically rather than just reading the state from persistent storage, then you can declare those variables with transient keyword. If there is a variable which is declared as transient, it will not be persisted during serialization.
Transient is a keyword applicable only to variables (only to class level variables),we cannot apply transient keyword for classes and methods.
class Point {
int p, q;
transient float f;
}
Here Object serialization process will save p and q but not f. Transient variables can be declared as static and final but will create certain situations . In case of static variable there is no meaning of declaring so, as the static variable is already class specific and will no be serialized. The final transient variable need to be initialized manually during deserialization process.
Volatile
A Java programming language uses the keyword ‘Volatile’ indicates that the variable declared volatile will be modified asynchronously by concurrently running threads. The volatile keyword is very useful when the variables are shared by many threads . Volatile declaration tells the compiler that the variable need to be fetched as fresh , rather than caching them in registers during each call. This ensures that the latest value of the variable is fetched..
public class Volatile_Demo
{
volatile int var ;
}
Volatile fields is considered to be a little slower than normal non-volatile fields, because the system need to keep this variable in memory rather than in registers. Volatile variables need to be synchronized with the main memory copy always. Volatile variables has the features of synchronized, but it doesn’t have any of the atomicity features. The Volatile can provide thread safety, but only in a limited situations where
- No constraints between multiple variables
- No constraints between a variable’s current value and its future values.
The volatile and Transient modifiers has its own advantages during development ,the key features are the simplicity and scalability