javakryo

Kryo serialization system, how does it ensure that same ID will be generated when registering the same class


I check the source code of Kryo, it seems that when registering a class, it uses auto increment ID for it, if this is the case, what will happen if the writer and reader use different registeration order,

# writer
kryo.register(Foo.class);
kryo.register(Bar.class);
# reader
kryo.register(Bar.class);
kryo.register(Foo.class);

Will the deserialization still work? If not, wouldn't this be a problem? Because there's a pretty high possibility that writer and reader are not in the same application, therefore no easy way to ensure both register classes in the same order, right? Or am I missing something here?


Solution

  • If we use the automatically generated IDs then deserialization won't work if the order of registrations is different. It is mentioned in Kryo's documentation .

    During deserialization, the registered classes must have the exact same IDs they had during serialization. When registered, a class is assigned the next available, lowest integer ID, which means the order classes are registered is important.

    There is an option to pass an integer ID while registering the class. This way, we don't have to worry about the order.

    kryo.register(Foo.class, 1);
    kryo.register(Bar.class, 2);
    

    You can also make those IDs a static final member of the class.

    class Foo {
      public static final int KRYO_ID = 1;
    }
    .
    .
    .
    kryo.register(Foo.class, Foo.KRYO_ID);