Monday, April 11, 2016

Transient Keyword in java with Example

Before going to examine the Transient keyword, we should know what is serialization and de-serialization. 

What is Serialization ?

Serialization is the process of converting your object into stream of bytes and stored in a file. These process will be handled by JVM and mostly it will be involved in networking side.If any class want to be involved in serialization then it must implements serializable interface. 

What is De-Serialization ?

The same process again bring back your object states to bytes called de-serialization.

What is transient Keyword in java?

If any variables declared transient keyword in java which will not be participated in serialization. Means, It indicates to JVM the transient varibale is not part of the persistence state of an object. 

Lets see one simple example to understand further.
Person.java


import java.io.Serializable;

public class Person implements Serializable {    

    private String name;

    private int id;

    private transient String characterType;
     

    public Student(String name, int id, String characterType) {

        this.name = name;

        this.id = id;

        this.characterType = characterType;

    }

    @Override

    public String toString() {

        return "Name: " + name +

                ", id: " + id +

                ", characterType : " + characterType;

    }

}
MainTest.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; 

public class MainTest {

    public static void main(String[] args) throws ClassNotFoundException {

        Person p = new Person("TestName", 1, "Good");

        System.out.println("Before serialization:" + p.toString());

        // Below is the way to Serialize of the object

        try {

            FileOutputStream file = new FileOutputStream("p.ser");
            ObjectOutputStream out = new ObjectOutputStream(file);
            out.writeObject(p);
            
            System.out.println("Object P was serialized");
            out.close();
            file.close();

        } catch(IOException e) {
            e.printStackTrace();

        }

        // Deserialization of the object.

        try {

            FileInputStream file = new FileInputStream("p.ser");
            ObjectInputStream in = new ObjectInputStream(file);
            Person p1 = (Person) in.readObject();

            System.out.println("After de-serialization :" + p1.toString());
            in.close();
            file.close();

        } catch(IOException e) {

            e.printStackTrace();

        }

    }

}

In the person java class we have used toString() to identify how the variables will be printed.Lets execute the program and check the output. 


Before serialization:
Name: TestName, id: 1, characterType: Good

Object P was serialized

After de-serialization :

Name: TestName, id: 1, characterType: null 
From the above output we able to see charaterType is null, since it used transient keyword and its not participated serialization. Remember static variables also will not participate in serialization process. Since its not belongs to any individual instance.

Lets go somewhat deep into this. 

Transient with final Keyword

Just consider you have below code with final declaration. 

private String name;
public final transient String userName = "TestUserName";
public final transient Logger logger = Logger.getLogger(Test.class);
Once we execute this above code, output will be too much different. Output is below. 
Name
TestUserName
null
As per serialization concept the TestUserName should be display value as null. But logger was displaying null perfectly. The reason is, String userName is mentioning constant Expression. logger mentioning reference. So logger returning null.

If we remove transient from both logger and userName , userName will be involved in serialization and logger will not be involved and will throw NotSerializableException

See below String API. Its implementing Serializable interface and logger not implementing.
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

No comments:

Post a Comment