I was reading the source of Java's ArrayList and I came across its backing array declaration:
private transient Object[] elementData;
Why does this need to be transient? Why can't this class be serialized?
Thanks for the help!
Transient in Java is used to mark the member variable not to be serialized when it is persisted to streams of bytes. This keyword plays an important role to meet security constraints in Java. It ignores the original value of a variable and saves the default value of that variable data type.
The transient keyword in Java is used to avoid serialization. If any object of a data structure is defined as a transient , then it will not be serialized. Serialization is the process of converting an object into a byte stream.
When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. transient keyword plays an important role to meet security constraints. There are various real-life examples where we don't want to save private data in file.
A transient variable is a special type of variable which we create by using the transient keyword. It is a special type of variable which have a non-serialized value at the time of serialization. A variable that is initialized by its default value during de-serialization is known as a transient variable.
It can be serialized; the ArrayList
class just takes care of things itself, rather than using the default mechanism. Look at the writeObject()
and readObject()
methods in that class, which are part of the standard serialization mechanism.
If you look at the source, you see that writeObject()
does not save the backing array. Instead, it serializes the elements (including null values) one at a time up to the size()
limit. This avoids the overheads of serializing the array, and especially any unused slots at the end of the array. On deserialization, a new backing array of the minimum required size is created by readObject()
.
Why does this need to be transient?
It does this because it provides custom readObject
and writeObject
methods that do a better job of serialization than the default. Specifically, the writeObject method writes just the size and the sequence of elements. This avoids serializing the private array object which 1) has its own header and overheads, and 2) is typically padded with null
s. The space saving can be significant.
Why can't this class be serialized?
The ArrayList
class as a whole can be serialized1. The Object[]
could be serialized directly, but they chose to mark it as transient
implement the serialization another way.
1 - Actually, this depends on the elements' runtime types. For example, if you attempted to serialize an ArrayList
containing Thread
references, then you would get a runtime exception for the first non-null reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With