Transient variables are indeed not considered when an object is being serialized. It is usually used for variables that cache the result of a method that may be called often. For example, if you have an expensive hashCode() method, you may calculate the hash once and store it in a variable and return that value every time the hashCode() method is called after that. When the object is being serialized, the process is free to discard the value, because it can be easily be recomputed again.
Volatile variables tell the JVM that threads are not allowed to store values assigned to them into cache, but have to write it to memory immediately. It ensures that different threads of execution see the same value when they query the variable. It's a rarely used keyword, since it is only useful in very specific conditions.
If a class has a transient variable and you are using multi threading ,then each thread must reconcile its copy of a transient variable from main memory.
If any thread using the transient variable modifies that variable then the thread must have to write it to memory immediately, and the other threads must reconcile their copy
of the variable from main memory before using it.
The important thing is not to stop questioning.Curiosity has its own reason for existing.
while posting reply ,may be Im thinking something else!!!
Joined: Apr 25, 2011
Thanks for the information Stephan and Vijay
I have found one more view to understand volatile :
volatile is usually used in threads. In threading there are two types of memory. Main memory and threads’ local memory.
Threads’ local memory is like a screen shot of main memory. So screenshot is not necessarily the current state of the main memory but the state when screenshot is taken.
volatile tells the thread not use screenshot of variable but use main memory instead which is always updated.