Should a serialized Java object always be represented by the same sequence of bytes every time it is serialized?

For example, if an object instance was serialized (the result is "byte [] bs1"), then it is serialized again (the result is "byte [] bs2") if "bs1" and "bs2" must be the same length and contain those same bytes? If not, why not?

To avoid ambiguity, I have to say that two serializations of the same object (and not two identical objects - the same instance) occurred milliseconds from each other in the same thread on the same JVM - the object (mutable) was passed to the method, one after it.

Note that the object is not even serialized, deserialized, and then re-serialized - it is just serialized twice. In addition, there is nothing β€œsmart” about the class of an object; it's just a simple POJO unit.

I use serialized bytes as a special test to determine if an object has been modified inside a method. However, it seems that I see examples where an object has not explicitly changed its state, but one byte [] is different from another.

I assumed - and it was just an assumption that they would be the same. Is there a reason they cannot be?

Application:

Also, sorry for the lack of code to illustrate this point. This is currently a small piece of code embedded in a large system. If necessary, I will try to extract a smaller demo version. I wondered if there was a major problem with my assumption, and therefore, if anyone could explain why the assumption is wrong.

+8
java serialization
source share
1 answer

It may not always be the same sequence of bytes that is created through serialization. For example, the order in which a Set serializes its elements is not guaranteed to be constant, even if we are talking about a single instance.

+5
source share

All Articles