Friday, September 9, 2011

How to work with transient variable in java (an example tutorial)

Transient keyword in java is comparatively less common than any other keyword like volatile.since transient is less common it becomes even more important to understand correct usage of it. In One word transient keyword is used in serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.In this article we will revise some basics like
What is transient variable in java, why do we need transient variable and most importantly where should we use transient variable or which fields need to be declared as transient with example.

What is transient variable in Java?

transient variable, transient keyword javaIn simple sentence any variable which is modified with transient keyword becomes transient variable in java.But before understanding about transient variable let recap something about serialization in java. Serialization is a process by which object's state is saved by JVM and during deserializaiton it’s recovered by JVM. During Serialization all property of object gets saved except static and transient. So if we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it. While marking any property transient its worth noting to provide it a default value during deserialization otherwise deserialized object is not properly usable.

Why do we need transient variable in java?

Transient keyword provides you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process. Some time it does make sense not to serialize certain attributes of an object, we will see which variables should not be serialized and should be made transient in next section.

Which variable you should mark transient?

This is a good question; since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient. My rule is that any variable whose value can be calculated from other variables doesn't require to be saved. For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.

Another example is of word count, if you are saving article then no need to save word count, because it can be created when article gets deserialized. Another good example of transient keyword is "Logger" since most of the time you have logger instance for logging in Java but you certainly don't want it to serialize correct?

Example of transient variable in java

To understand the concept of transient variables let see a live example in java.


public class Stock {
    private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
    private String symbol; //will be serialized
    private BigInteger price; //serialized
    private long quantity; //serialized
}

Important points about transient keyword in java

Here are few important points about transient variables in java which I found, let me know if you have some more which I missed out here and I will include here.

1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.

2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.

3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of reinitializing a final variable during deserialization.

4) Transient variable in java is not persisted or saved when an object gets serialized.


That's all from me on transient keyword, let me know how do you use it and if you know any pecularity about transient keyword or something which we need to be aware while using it and missed out here. You can also refer’s Sun Glossary for meaning of different keywords in Java.


Related tutorials in Java


6 comments :

Anonymous said...

transient keyword also saves you with NotSerializable exception. If you have a field in your Class which does not implement Serializable interface than there is no way out other than marking it transient.

Anonymous said...

Does it make sense to have a trasient variable if your class is not serializable?

Vedu said...

@Anonymous, Yes if you have an non serializable class which is part of Serializable than you can not include that into default Serialization, you have two option either declare them static or transient. further if they are class level resource than making static more sense than transient.

Anonymous said...

can you please explain in simple terms what is transient variable in Java and where to use transient variable ? the definition looks very technical, a simple example or real life use case would be appreciated.

Ramana Venkat M N said...

Hi all,
I have a question,
I declared an object (which has 3 properties String, int, double) itself as transient.
I call oos.writeObject(object1);
and then when I call
object2 = (MyClass) ois.readObject();
It is successfully deserialized even though it is declared as transient.

Can anybody explain please!!

Anonymous said...

I see contradictions in your statements..

see point 2 here.. 2) Another important point is that you can declare an variable static and transient at same time.....

and another point on page --
http://javarevisited.blogspot.sg/2012/03/difference-between-transient-and.html
which says...
2) transient keyword can not be used along with static keyword but volatile can be used along with static.

Post a Comment