Saturday, September 9, 2017

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 the correct usage of it. In one word transient keyword is used in the 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 a transient variable, and most importantly where should we use a transient variable or which fields need to be declared as transient with example.

What is a transient variable in Java?

transient variable, transient keyword javaIn a simple sentence, any variable which is modified with transient keyword becomes a transient variable in java. But before understanding about transient variable let recap something about serialization in java. Serialization is a process by which the object's state is saved by JVM and during deserialization, 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 used.

Why do we need a transient variable in java?

The transient keyword provides you some control over the serialization process and gives you the flexibility to exclude some of the object properties from the serialization process. Sometimes 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 the 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 makes 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 like principal, 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 the article gets deserialized. Another good example of a 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 correctly?

1. Example of a 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

2. Important points about the 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) A transient keyword can only be applied to fields or member variables. Applying it to the method or local variable is a compilation error.

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

3) In a 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) A 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 peculiarity about transient keyword or something which we need to be aware while using it and missed out here. You can also refer Sun Glossary for the meaning of different keywords in Java.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Related tutorials in Java


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.

Unknown 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 --
which says...
2) transient keyword can not be used along with static keyword but volatile can be used along with static.

Post a Comment