Any real time example for transient variable in java

Shashi picture Shashi · Jan 22, 2014 · Viewed 19.4k times · Source

From the question Why does Java have transient fields?. I am able to understand the transient. But, not able to evaluate to using transient keyword at the time of designing.

public class A implements Serializable 
{
    public String s;
    public transient ts; 
}

If i do the same thing in alternative way..

public class A implements Serializable 
{
    public String s;
    //public transient ts;//removing this variable.

} 

And use another class and define method inside the class and define the variable ts and do the operation and persist the value of s as business defines.

QUESTION

I didn't find any real time example in the web where i will take decision to define a variable transient.

How could i take the decision to define transient at the time of designing? Is there any realtime scenario that helps me to understand?

Answer

Makoto picture Makoto · Jan 22, 2014

To put it plainly: any field marked as transient is not saved if/when the object is serialized.

Let's say, for instance, you have an entity that needs to be serialized, but this entity has a data field that is, in a word, massive:

public class SerializeMe implements Serializable {
    private Integer id;
    private String value;
    private BigMatrix bigMatrix = BigMatrixFactory.fromValues(id, value).build();

    public BigDecimal doExpensiveOperation() {
        BigDecimal result = BigDecimal.ZERO;
        for(BigDecimal value : bigMatrix.getAllValuesFromAllMatrixFields() {
            matrixMultiply(result, value);
        }
        return result;
    }
}

You really don't want that BigMatrix to be serialized, since you'd be serializing a huge quantity of data which isn't necessary to rebuild the object (note, it can be built simply by using the builder pattern, given the ID and value).

In a trivial example, this may not be that big of a deal. But if you were sending this particular entity across a network, that would be a huge deal - you now have the expense of transferring not only the entity you want, but also some internal state about it that can be generated.