Forums Register Login

Serialization of static variables

+Pie Number of slices to send: Send
I read java serialization doesn't include static variable's data. But when i run the following java file it does. It retains the value of the static variable. Can anyone explain why

Code

Output :


Before Serialization :x : 8, y :20
ABCfter Serialization :x : 0, y :20



If you observe the static variable y before serialization is initialized to 9 and later changed to 20 in constructor. After serialization is done. Now Deserializing the class shouldn't retain the static variable content according to my assumption : "java serialization doesn't include static variable's data". Why is this happening.
1
+Pie Number of slices to send: Send
Welcome to the Ranch!

Variable y is static. That means that as long as the class is loaded, it will keep the same value. You are serializing and de-serializing inside the same JVM instance.

Try splitting the serialization and de-serialization into two classes and see the difference:
Now run java SerTest first, then java DeSerTest.

And please UseCodeTags next time.
+Pie Number of slices to send: Send
Thanks Rob for your reply. I'll definitely take your suggestions.

I want to check whether i understood the behavior of the code properly.


In the above code i have posted.


Serialization Process.

Will not store the static information.


Desirialization Process.

Will get the static field information by loading the class. As the class ABC is already
loaded into the JVM, it refers to the static field which is already existing in the memory.
As it is changed in the constructor, the deserialization would pick the changed one from the memory.



Is this understanding proper.
+Pie Number of slices to send: Send
That looks to be a good summary, yes.
Because those who mind don't matter and those who matter don't mind - Seuss. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 5041 times.
Similar Threads
java.io.StreamCorruptedException: invalid stream header:i understand its a thread issue not sure fix
readObject() eat memory !!!
paritial serialization
Behaviour of static variables
Query
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 06:46:00.