Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialization of static variables  RSS feed

 
Sandeep Reddy Vinta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sandeep Reddy Vinta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks to be a good summary, yes.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!