Does kryo support cyclical graphs

127 views
Skip to first unread message

tauzell

unread,
Sep 29, 2009, 3:37:55 PM9/29/09
to kryo-users
I'm serializing a data structure that has a "parent" reference. When
Kryo gets here it goes into an infinite loop. I'm guessing that Kryo
doesnt support this type of construct?

Nate

unread,
Sep 29, 2009, 6:00:11 PM9/29/09
to kryo-users
Not automatically at this time, no. The logic needed to support this
automatically would affect all serializers that serialize other
objects. I'm not convinced the extra runtime logic and code complexity
is worth it.

However, you can do the parent reference bit yourself. First either
set the "parent" field on the child class to transient, or if you
don't control the source you can tell FieldSerializer not to serialize
it:

FieldSerializer childSerializer = new FieldSerializer(kryo);
// The removeField method is in SVN only right now.
childSerializer.removeField(Child.class, "parent");
kryo.register(Child.class, childSerializer);

Next, when you serialize the parent class, manually set the "parent"
field on the child instances:

kryo.register(Parent.class, new FieldSerializer(kryo) {
public Parent readObjectData (ByteBuffer buffer, Class<Parent> type)
{
Parent parent = super.readObjectData(buffer, type);
for (Child child : parent.getChildren())
child.setParent(parent);
return parent;
}
});

Another way to do this, if you control the source, is to have the
parent class implement CustomSerialization and do the "setParent"
stuff there.

This is not as convenient as having it handled automatically, but I
don't think serializing cyclic graphs is typical usage. Also, the
above is more efficient since it does not need to serialize anything
for the "parent" references on the child class.

-Nate
Reply all
Reply to author
Forward
0 new messages