Java - why transient member variables used so widely in Java standard library?

From serialization point of view transient variables will not be serialized when serializing the whole object.

When you don't want some variable to be serialized you make it transient

From your example LinkedList is serializable. If you look carefully all the variable that are made transient are maintained programmatically. SO there is no need to persist them.

For example size, when you are reading back any serialized object you are reading just Node<E> and maintaining the size programmatically. So there is no need to serialize the size. Remember the real data of a LinkedList is not its size. If you have the real data which are the entries you can calculate its size any time and its easier this way.

For Reference please have a look.

@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    // Read in any hidden serialization magic
    s.defaultReadObject();

    // Read in size
    int size = s.readInt();

    // Read in all elements in the proper order.
    for (int i = 0; i < size; i++)
        linkLast((E)s.readObject());
}

void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

Tags:

Java

Transient