What is the use of transient variables?

muralidhar picture muralidhar · May 11, 2011 · Viewed 13.1k times · Source

Possible Duplicate:
Why does Java have transient variables?

The transient keyword will be used to prevent serialization of a particular variable. But why should we not to serialize the data? Is there any inner security?

Answer

Joachim Sauer picture Joachim Sauer · May 11, 2011

Some classes are inherently not serializable, because they represent resources outside of the manage Java environment. For example a FileOutputStream can't really be serialized, because it represents an open file handle. The same is true for a Socket: you can't save and restore "open sockets".

If you want to serialize some object that has a field of that type, then you'll have to mark those fields as transient.

Another reason to use transient is when your class does some kind of internal caching. If, for example, your class can do calculations and for performance reasons it caches the result of each calculation, then saving that cache might not be desirable (because recalculating it might be faster than restoring it, or because it's unlikely that old cached values are of any use). In this case you'd mark the caching fields as transient.