Originally posted by bhuvi mdu:
why transient variable cannot be serialized?
It's been explained a couple times in this thread, but just in case it wasn't crystal clear: Java's transient keyword tells the serialization system to ignore the fields when writing and to initialize them the same way instance fields are initialized during reading.
Here's another example from the JDK itself. The standard Collection classes introduced in JDK 1.2 can cause intermittent exceptions or simply "unexplainable" behavior under specific multi-threaded conditions, even if you synchronize all calls to its methods. One such condition is when any thread calls a method that structurally
modifies it while one thread is using its Iterator.
For example, changing a value in a Collection doesn't alter the its structure. But adding a new value can. In a TreeSet, adding a new value requires inserting a new node somewhere in the tree. Any live Iterators will have an internal state that's no longer consistent with the TreeSet. Trying to return the next element might return the wrong element (skipping some or jumping back in the sequence) or one that was removed.
Sun's solution was to add an instance variable (called modCount) that tracks the number of times the Collection has been structurally modified. When an Iterator is created, it stores a copy of modCount. At the start of each method -- hasNext(), next(), and remove() -- it checks its copy against the Collection's current value. If they differ, it throws a ConcurrentModificationException.
[ Note to self: examples aren't very good if they require three paragraphs to provide background that's necessary but in the end doesn't really relate to the topic at hand. My bad.
In any case, if you serialize the Collection and then deserialize it some time in the future, you receive a new reference to a new Collection. It's physically impossible for any object in memory to hold a reference to it. Therefore, there's no point in storing modCount; it can safely be initialized to 0.
What about any Iterators on that Collection that were serialized with it? It would be a problem only if the Collection's Iterators implemented Serializable. I checked ArrayList's, and it isn't in JDK 1.5.0. I suspect none of them are as serializing an Iterator seems marginally useful at best.