How do I determine that I am in the last byte of a serialized Java object?

Question

What are (if any) trailing characters / byte sequences in serialized java objects?

Background

I am working on a small self educating project where I would like to serialize java objects and write them to a stream where there are read and then unserialized. Since I will need to determine the boundaries between serialized objects and I cannot be sure that the current object is not the last one, is there a trailing character that always exists that I can use as my identifier?

I noticed that there is a magic ACED number that allows me to identify the beginning of an object, so how can I determine the end?

EDIT: If there is no trailing character, are there any safe trailing characters / sequences that I can use (insert) to identify the end of the object?

0


a source to share


4 answers


In theory, you should always be able to find the end of an object; in practice, you cannot. I understand that the problem is to configure the writeObject

implementations that do not cause any defaultReadObject

, or readFields

have non-standard performance.

I've played around with serialization in the past. Including creating threads to use when I did unusual things for ObjectInputStream

. It is unpleasant (!).



You can read the details in the spec and the source is well worth reading.

+2


a source


there is none of them. AFAIK the only requirement is that the deserializer knows when to stop reading when given the appropriate serialization. provided that the serializer can write whatever it wants - in any position, not only the last one.

if you old skool dump a 32-bit length field at the start of failing to handle objects larger than 4 gigabytes.



nu scool, you just make sure your read and your write logic are consistent and don't care about length.

+1


a source


You can add a terminating object to the object stream. for example null or a special string.

However, I suggest you convert the ObjectStream to byte [] instead, and write the length of the byte byte [] followed by its data. This way, each ObjectStream is independent and you always know where it ends.

+1


a source


Do you think you are using a recording layer similar to the HTTP Chunked encoding ?

Chunked encoding is intended to address the generalization of this scenario: identifying the end of a message of indefinite length, which itself does not contain an identification end, and is embedded in a longer stream without termination.

0


a source







All Articles