kryo icon indicating copy to clipboard operation
kryo copied to clipboard

Allow turning a few optimisations off for Kryo 5.4.0

Open chrisr3 opened this issue 1 year ago • 20 comments

We are upgrading our code-base from Kryo 4.0.2 to 5.4.0, and have hit an issue when serialising a Collection that only contains instances of Collections$UnmodifiableRandomAccessList.

We have sub-classed Kryo to support serialising classes with writeResolve and readReplace methods; UnmodifiableRandomAccessList implements writeResolve like this:

private Object writeReplace() {
    return new UnmodifiableList<>(list);
}

Kryo 5's CollectionSerializer seems to have an optimisation for the case when all of a collection's elements are of the same type, whereby Kryo serializes the element type once, and then serializes all of the elements' object data afterwards. Unfortunately, UnmodifiableRandomAccessList.writeResolve transforms the elements into instances of UnmodifiableList, but Kryo is unable to discover this until it has invoked writeResolve at least once. This happens after it has incorrectly written UnmodifiableRandomAccessList as the element type to the output stream, of course.

I cannot see a way of working around this apart from ignoring UnmodifiableRandomAccessList.writeResolve, although I cannot ignore every writeResolve method because that would break lambda serialization. Ideally, I'd like to be able to configure CollectionsSerializer not to apply this optimisation at all.

chrisr3 avatar Mar 19 '23 20:03 chrisr3